Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script Exit Code - Unable to set

Tags:

bash

shell

exit

I am running following test bash script:

test.sh

========

pass=$1
if [ $pass -eq 1 ]; then
   exit 0
else
   exit 1
fi

=============

So, If I run './test.sh 1', it should give me success code, i.e. 0. And if I run './test.sh 2' it should give me specific error code, i.e. 1.

But when I run the script, I am getting 0 as exit code for both the cases.

Output

========================

# ./test.sh 1 |echo $?
  0
# ./test.sh 2 |echo $?
  0
#

=========================

What am I doing wrong here? Any help will be greatly appreciated!

Noman A.

like image 689
Noman Amir Avatar asked Aug 14 '26 12:08

Noman Amir


1 Answers

Your script works, your test is broken though. Don't use a pipe there.

# ./test.sh 1 ; echo $?
0
# ./test.sh 2 ; echo $?
1

What you proposed with a pipeline cannot work, because all the processes in pipeline are started "simultaneously". The shell starts a sub-shell to host each process (at least Bash does, implementations might vary -not sure about that), connects the input and output streams appropriately, then lets the OS schedule things as it sees fit.

So the rightmost process (in your case echo $?) is started at the "same time" as your test script. Therefore $? in that sub-shell (which will have been expanded before the actual process is started) can't possibly represent the return code from the test script - t.sh might not even have started yet!

See the Wikipedia article on Unix Pipelines for some more information, or your shells documentation on pipelines. (Bash Pipelines for instance.)

like image 149
Mat Avatar answered Aug 17 '26 03:08

Mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!