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
Related videos on Youtube
![Questionmark](https://i.stack.imgur.com/6NneQ.jpg?s=256&g=1)
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, 2022Comments
-
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 returns0
because it successfully set the variable to the output of the command.Is it possible to get the return value of
command
? -
Lennart Rolland about 6 yearsGold! But I spent a few minutes noticing the quotation marks :)
-
cwingrav almost 5 yearsInside a function, if you use 'local', it seems to not work. Just FYI.
-
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 over 4 years@Kusalananda - agreed. I should have updated my comment to include this (I figured it out shortly after).