开发者

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

开发者 https://www.devze.com 2023-02-17 05:33 出处:网络
I have the following: [root@alexandra SCB]# cat test_exit.sh #!/usr/bin/ksh if [[ -e \"test_exit.sh\" ]]; then

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]开发者_JS百科
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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消