Can I get the exit code from a sub shell launched with $(command)?

20,099

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
Share:
20,099

Related videos on Youtube

Questionmark
Author by

Questionmark

Believe me, this actually means something: ________ _jgN########Ngg_ _N##N@@"" ""9NN##Np_ d###P N####p "^^" T#### d###P _g###@F _gN##@P gN###F" d###F 0###F 0###F 0###F "NN@' ___ q###r "" My name is Mark... Get it?

Updated on September 18, 2022

Comments

  • Questionmark
    Questionmark almost 2 years

    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?

  • Lennart Rolland
    Lennart Rolland about 6 years
    Gold! But I spent a few minutes noticing the quotation marks :)
  • cwingrav
    cwingrav almost 5 years
    Inside a function, if you use 'local', it seems to not work. Just FYI.
  • Kusalananda
    Kusalananda over 4 years
    @cwingrav It works if you separate the local declaration from the assignment into two separate steps: local var; var=$(exit 3); echo "$?"
  • cwingrav
    cwingrav over 4 years
    @Kusalananda - agreed. I should have updated my comment to include this (I figured it out shortly after).