Reputation: 953
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.
Upvotes: 2
Views: 2554
Reputation: 206689
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.)
Upvotes: 11