0

I have a script like this, named judge:

#!/bin/bash
echo "last exit status is $?"

It always outputs "last exit status is 0". Eg:

ls -l;   judge # correctly reports 0
ls -z;   judge # incorrectly reports 0
beedogs; judge # incorrectly reports 0

Why?

2
  • I'm guessing the answer is "$? is local to the current shell process and the script is a subprocess" Mar 9, 2016 at 17:09
  • 2
    That is exactly why. There are different bash processes executing each line of code and $? isn't shared between the processes.
    – Bratchley
    Mar 9, 2016 at 17:12

2 Answers 2

2

There are different bash processes executing each line of code and $? isn't shared between the processes. You can work around this by making judge a bash function:

[root@xxx httpd]# type judge
judge is a function
judge ()
{
    echo "last exit status is $?"
}
[root@xxx httpd]# ls -l / >/dev/null 2>&1; judge
last exit status is 0
[root@xxx httpd]# ls -l /doesntExist >/dev/null 2>&1; judge
last exit status is 2
[root@xxx httpd]#
1

As discussed in the comments, the $? variable holds the value from the last process that returned a value to the shell.

If judge needs to do something based on a previous command state, you could have it accept a parameter, and pass in the state.

#!/bin/bash
echo "last exit status is $1"
# Or even 
return $1

So:

[cmd args...]; judge $?
1
  • Oops, transcription error. I meant "$1".
    – user156990
    Mar 9, 2016 at 17:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .