4

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.

9

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

$ $(exit 3); echo $?
3

$ foo="$(echo bar; exit 3)"; echo $?; echo $foo
3
bar
  • Gold! But I spent a few minutes noticing the quotation marks :) – Lennart Rolland Apr 17 '18 at 8:03

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