Dancrumb
Dancrumb

Reputation: 27549

How do I set an exit code from within a shell conditional?

I have the following:

[root@alexandra SCB]# cat test_exit.sh
#!/usr/bin/ksh

if [[ -e "test_exit.sh" ]]; then

  echo "No existential crisis here"

   fake_command

  if [[ $? -ne 0 ]] ; then
    echo "You can't run fake commands"
    exit 256
  fi
else
  echo "WTF?"
fi

[root@alexandra SCB]# ./test_exit.sh
No existential crisis here
./test_exit.sh[7]: fake_command: not found [No such file or directory]
You can't run fake commands

[root@alexandra SCB]# echo $?
0

My expectation is that I should get 256, not 0.

I seem to recall reading somewhere that an if conditional in KornShell spawns a child process. At first, I thought that could be the problem, but even that does not explain it. If my memory about that is correct, the for process would exit with $? == 256. All other exits would be an implicit exit $? and this would propagate the value of 256 all the way back to the original shell.

Can anyone explain why I am not seeing the 256 that I am expecting to see?

Upvotes: 1

Views: 4492

Answers (2)

Henk Langeveld
Henk Langeveld

Reputation: 8456

A side note: It is a good idea to limit exit codes to 1..127 to stay compatible with 'wait'.

The wait command will return the lower 7 bits of the status of the last background process to complete. Values over 128 are used to indicate the signal number that killed the other process.

Upvotes: 2

M'vy
M'vy

Reputation: 5774

That is because 256 exceed the total number allowed for a 8 bits value. If you use 255 it would work.

256 == 0 modulo 256 as 2^8 = 256

Upvotes: 4

Related Questions