How to Make `local` Capture the Exit Code in Bash

bashexit-statusvariable

In my project I have the following snippet:

local output="$(bash "${1##*/}")"
echo "$?"

This always prints zero due to local, however, removing local causes the $? variable to behave correctly: which is to assume the exit code from the subshell.

My question is: how I can keep this variable local whilst also capturing the exit value?

Best Answer

#!/bin/bash
thing() {
   local foo=$(asjkdh) ret="$?"
   echo "$ret"
}

This will echo 127, the correct error code for "command not found".

You can use local to define more than one variable. So I just also create the local variable RET to capture the exit code of the subshell before local succeeds and sets $? to zero.