I have a command in a function whose output is placed in a local variable. I want to get the exit status of that command, but $? always returns 0. When I use a non-local variable I get the expected exit status.

Here's an example:

function my_fun() {
   local output=$(ls no_file_here_buddy)
   echo $?  # returns 0

   non_local_var=$(ls no_file_here_buddy)
   echo $? # returns 2

How do you get the exit status of a command whose output is stored in a local variable?


When using local, the $? contains the exit code of local, not of your command. Just separate the declaration of the variable from the assignment:

local output
output=$(ls no_file_here_buddy)
echo $?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.