13

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?

26

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
|improve this answer|||||
  • Gold! But I spent a few minutes noticing the quotation marks :) – Lennart Rolland Apr 17 '18 at 8:03
  • 2
    Inside a function, if you use 'local', it seems to not work. Just FYI. – cwingrav Jul 9 '19 at 10:56
  • 3
    @cwingrav It works if you separate the local declaration from the assignment into two separate steps: local var; var=$(exit 3); echo "$?" – Kusalananda Dec 28 '19 at 7:24
  • @Kusalananda - agreed. I should have updated my comment to include this (I figured it out shortly after). – cwingrav Dec 29 '19 at 12:18

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