Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the exit status of second last command?

Tags:

bash

shell

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 image 273
akshaybetala Avatar asked Dec 23 '22 17:12

akshaybetala


2 Answers

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.

like image 119
Charles Duffy Avatar answered Feb 02 '23 02:02

Charles Duffy


cmd1; status=$?; cmd2 && echo $status
like image 25
RaphaMex Avatar answered Feb 02 '23 02:02

RaphaMex