I want to run 2 commands and output the exit status of the first command. And all this, I want to do it in a single line of command. Something like this
cmd1; cmd2 && echo $?-1
It should output the exit status of cmd1.
Like any other global variable that has its status updated over time (ie. errno
in C), if you want to refer to an old value, you need to store it ahead-of-time.
cmd1; cmd1_retval=$?; cmd2 && echo "$cmd1_retval"
The place where this is different, by the way, is in a pipeline:
cmd1 | cmd2 | cmd3
echo "${PIPESTATUS[$(( ${#PIPESTATUS[@]} - 2 ))]}"
That's because in a pipeline, all components run at once, and by default the exit status is that of the last one. In bash, however, the exit status of all components is stored in the PIPESTATUS
array; ${#PIPESTATUS[@]}
takes the length of this array, and subtracting two from it (one because of the difference between 0- and 1-based indexing, and one to get from the last item to the second-to-last item) gets the second-to-last item in the preceding pipeline.
cmd1; status=$?; cmd2 && echo $status
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With