why is the exit status saved in a variable changing (bash shell)?

117 views Asked by At

I have the following executable files:

set_status.sh
    #!/bin/bash
    exit $1
tst_set_status.sh
    #!/bin/bash
1.  echo arg1 = $1
2.  ./set_status.sh $1
3.  stat=$?
4.  echo $?
5.  if [ $stat -eq 0 ]; then
6.    final_stat="ok"
7.  fi
8.  echo $stat
9.  echo `echo $?`

So:

./tst_set_status.sh 1

arg1 = 1
0
1
0

Questions:

  1. Why does $stat have the value 0 and not 1 at line 4? Is line 4 printing the result of the shell asignment on line 3?
  2. Which command exit status is the ? variable reporting in line 9?
1

There are 1 answers

6
hobbs On BEST ANSWER

Why does $stat have the value 1 and not 0 on line 6?

Because tar (or whatever was immediately before line 1) exited with a status of 1. $stat got the value of 1 on line 1, and didn't change afterwards.

The question you didn't ask is "why does echo $? print 0 on line 2?" And that's because the assignment on line 1 was a success, and so $? was reset to 0 before line 2.

Which command exit status is the ? variable reporting in line 7

The exit status of the echo on line 6.