Re: How to exit a shell script



On Mar 30, 5:46 pm, Keith Thompson <ks...@xxxxxxx> wrote:
mathieu <mathieu.malate...@xxxxxxxxx> writes:
  Could someone let me know why calling exit 1 from a shell scrip does
not exit the script ? I have something like

  cat input.txt | while read x; do set -- $x
    if [ "$#" != "2" ]
    then
      echo "Multiple parents: $x";
      exit 1
    fi;
  done
  exit 0

  However the message "Multiple parents" is properly printed but the
script continue to exit without error (0 returned).

I was suspicious of your statement that you have "something like"
what you posted.  It can be difficult or impossible to track down a
problem if all we have is "something like" the script that actually
exhibits the problem.

So here's a script that clearly exhibits the problem, with some extra
trace statements added:

#!/bin/sh

( echo 1 2 ; echo 3 4 5 ) | while read x; do set -- $x
  echo "\$x = $x, \$# = $#"
  if [ "$#" != "2" ]
  then
    echo "Multiple parents: $x";
    echo $$ Before exit 1
    exit 1
    echo $$ After exit 1
  fi;
done
echo $$ Before exit 0
exit 0
echo $$ After exit 0

The output I get is:

$x = 1 2, $# = 2
$x = 3 4 5, $# = 3
Multiple parents: 3 4 5
15380 Before exit 1
15380 Before exit 0

So the "exit 1" does do exit *something* (the statement following it is
not executed), but it doesn't terminate the script, whereas the "exit 0"
does terminate the script.  And both exit statement occur in the same
process, as shown by printing the value of $$.

I get the same output (with different values for $$, of course) sh,
bash, ash, dash, and ksh (on Ubuntu 10.10).  In zsh, the "exit 1" does
terminate the script.

I don't have an answer (and it's interesting that zsh behaves
differently), but maybe this extra information will help someone
else figure it out.

I had to change it to:


cat input.txt \
| while read x; do
set -- $x
if [ "$#" != "2" ]
then
echo "Multiple parents: $x";
exit 1
fi;
done
[ $? -ne 0 ] && exit 1

I never realized that exit was simply exiting a while loop and not
the whole script.

Thanks anyway
.