如何在 shell 命令或单行脚本上生成我想要的退出代码?

Sop*_*rez 6 shell exit-status

我想生成一些退出代码,比如 20。
但是如果我在 shell 上做:

$ exit 20
Run Code Online (Sandbox Code Playgroud)

外壳已关闭(X-Windows 案例)或我已注销(文本控制台案例)。当然,在 .sh 脚本中,这个命令可以正常工作。

我已经测试没有成功:

$ return 20
bash: return: can only `return' from a function or sourced script
$ break 20
bash: break: only meaningful in a `for', `while', or `until' loop
Run Code Online (Sandbox Code Playgroud)

有没有办法$?变量赋值?

Olo*_*rin 8

在子shell中退出:

(exit 20)
Run Code Online (Sandbox Code Playgroud)

或者你可以写一个函数:

ret () { return $1; }
ret 20
Run Code Online (Sandbox Code Playgroud)

  • @SopalajodeArrierez:因为它是从子shell 退出而不是您当前的shell。 (2认同)
  • 如前所述,子 shell 是由 `( ... )` 创建的。子shell中的exit只存在子shell,不存在原shell。 (2认同)