【问题标题】:Getting exit code of last shell command in another script在另一个脚本中获取最后一个 shell 命令的退出代码
【发布时间】:2012-10-11 13:52:21
【问题描述】:

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

例如:

sleep 100; my_notify

如果能得到长时间运行脚本的退出代码就好了。问题是调用my_notify 会创建一个无法访问$? 变量的新进程。

比较:

~ $: ls nonexisting_file; echo "exit code: $?"; echo "PPID: $PPID"
ls: nonexisting_file: No such file or directory
exit code: 1
PPID: 6203

对比

~ $: ls nonexisting_file; my_notify
ls: nonexisting_file: No such file or directory
exit code: 0
PPID: 6205

my_notify 脚本中包含以下内容:

#!/bin/sh
echo "exit code: $?"
echo "PPID: $PPID"

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

这可以做到吗?还是它与 shell 的工作方式根本不兼容?

我的 shell 是 Z shell (zsh),但我希望它也能与 Bash 一起使用。

【问题讨论】:

    标签: bash shell zsh exit-code


    【解决方案1】:

    您确实需要使用 shell 函数来完成此操作。对于像这样的简单脚本,让它在 zsh 和 bash 中运行应该很容易。只需将以下内容放入文件中:

    my_notify() {
      echo "exit code: $?"
      echo "PPID: $PPID"
    }
    

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        实现这一点的一种方法是使用 EOF 标记和一个主脚本,该脚本将创建您的 my_notify 脚本。


        #!/bin/bash
        
        if [ -f my_notify ] ; then
        rm -rf my_notify
        fi
        
        if [ -f my_temp ] ; then
        rm -rf my_temp
        fi
        
        retval=`ls non_existent_file &> /dev/null  ; echo $?`
        ppid=$PPID
        echo "retval=$retval" 
        echo "ppid=$ppid" 
        cat >> my_notify << 'EOF'
        #!/bin/bash
        
        echo "exit code: $retval"
        echo " PPID =$ppid"
        EOF
        
        sh my_notify 
        

        您可以根据自己的目的优化此脚本。

        【讨论】:

          猜你喜欢
          • 2018-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-21
          • 1970-01-01
          • 2022-12-07
          • 1970-01-01
          相关资源
          最近更新 更多