2

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.

1 Answer 1

11

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.)

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply Mat. But when I use echo inside the script as well instead of using pipe, it prints 0 for both.
I don't understand what you mean by that. Edit your question to show your new version and how you call it, or post a new question.
Sorry Mat, I used the test as posted by you and the result is fine. Can you please tell me what is the difference with using pipe instead?
@Noman Amir: edited my answer to clarify why the pipe approach cannot work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.