在另一个脚本中获取最后一个shell命令的退出代码

seb*_*ger 36 bash shell zsh exit-code

我正在努力增强我的通知脚本.脚本的工作方式是我把它放在一个长时间运行的shell命令后面,然后在长时间运行的脚本完成后调用各种通知.

例如:

sleep 100; my_notify
Run Code Online (Sandbox Code Playgroud)

获取长时间运行脚本的退出代码会很好,问题是调用my_notify会创建一个无法访问$?变量的新进程.

相比:

~ $: ls nonexisting_file; echo "exit code: $?"; echo "PPID: $PPID"
ls: nonexisting_file: No such file or directory
exit code: 1
PPID: 6203
Run Code Online (Sandbox Code Playgroud)

~ $: ls nonexisting_file; my_notify      
ls: nonexisting_file: No such file or directory
exit code: 0
PPID: 6205
Run Code Online (Sandbox Code Playgroud)

my_notify脚本包含以下内容:

#!/bin/sh
echo "exit code: $?"
echo "PPID: $PPID"
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来获取上一个命令的退出代码而不会过多地改变命令的结构.我知道如果我将其更改为更好的工作time,例如my_notify longrunning_command...我的问题将得到解决,但我实际上喜欢我可以在命令结束时解决它并且我担心第二种解决方案的复杂性.

这可以完成,还是从根本上与shell的工作方式不兼容?

我的shell是,zsh但我希望它也可以使用bash.

qqx*_*qqx 40

你真的需要使用shell函数来实现它.对于像这样的简单脚本,它应该很容易让它在zsh和bash中工作.只需将以下内容放在一个文件中:

my_notify() {
  echo "exit code: $?"
  echo "PPID: $PPID"
}
Run Code Online (Sandbox Code Playgroud)

然后从shell启动文件中获取该文件.虽然这可以从您的交互式shell中运行,但您可能希望使用$$而不是$ PPID.


Ign*_*ams 6

这是不相容的.$? 仅存在于当前shell中; 如果您希望它在子进程中可用,则必须将其复制到环境变量中.

另一种方法是编写一个以某种方式使用它的shell函数.