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.
Your script works, your test is broken though. Don’t use a pipe there.
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.shmight 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.)