如何在 shell 条件中设置退出代码?
我有以下内容:
[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
我的期望是我应该得到 256
,而不是 0
。
我似乎记得在某处读到过,KornShell 中的 if
条件会生成一个子进程。起初,我认为这可能是问题所在,但即使如此也不能解释它。如果我的记忆是正确的,for
进程将以 $? 退出。 == 256
。所有其他退出都将是隐式 exit $?
,这会将 256 的值一路传播回原始 shell。
谁能解释一下为什么我没有看到我期望看到的 256?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为 256 超出了 8 位值允许的总数。如果你用255就可以了。
256 == 0 模 256 为 2^8 = 256
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
旁注:最好将退出代码限制为 1..127 以与“等待”保持兼容。
wait 命令将返回最后完成的后台进程状态的低 7 位。超过 128 的值用于指示杀死其他进程的信号号。
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.