This question already has an answer here:

I am setting a variable like this:

myvar=$(command --params)

I want to check the exit code ($?) of my command afterwards. Checking $? like this always returns 0 because it successfully set the variable to the output of the command.

Is it possible to get the return value of command?

marked as duplicate by Wildcard, countermode, Satō Katsura, Thomas Nyman, Toby Speight Feb 23 '17 at 13:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


Yes, it is possible without even getting too far out of your way:

$ $(exit 3); echo $?

$ foo="$(echo bar; exit 3)"; echo $?; echo $foo
  • Gold! But I spent a few minutes noticing the quotation marks :) – Lennart Rolland Apr 17 '18 at 8:03
  • Inside a function, if you use 'local', it seems to not work. Just FYI. – cwingrav Jul 9 at 10:56

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