如何在 shell 条件中设置退出代码?

发布于 2024-10-22 07:57:20 字数 782 浏览 5 评论 0原文

我有以下内容:

[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凯凯我们等你回来 2024-10-29 07:57:20

这是因为 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

万劫不复 2024-10-29 07:57:20

旁注:最好将退出代码限制为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文