使用'$ PROMPT_COMMAND'时保留退出代码

时间:2014-06-24 19:00:21

标签: bash shell exit-code

我有以下代码(simplified for clarity),在每个命令后由$PROMPT_COMMAND调用:

function previous_command_status() 
{
    exit_code=$?;
    if [ $exit_code -eq 0 ]; then
        echo "Command successful"
    else
        echo "Command failed with exit code $exit_code"
    fi
}

问题是,似乎[ $exit_code -eq 0 ]部分正在更改退出代码,因此在命令运行完毕后我无法使用或存储退出代码。例如:

$ ./failing_script.sh
Command failed with exit code 255
$ echo $?;
1   # this is the exit code of the 'if' statement, not of 'bad'

我无法"传递值",因为如果我在函数内添加行exit $exit_code,终端窗口会立即关闭

我有什么方法可以保存"上一个命令的退出代码,或以一种他们不会修改退出值的方式运行一组命令?

1 个答案:

答案 0 :(得分:3)

你无法保留它。即使您使用case语句,echo仍会改变它。但是,您可以使用return

将其恢复
exit_code=$?;
if [ $exit_code -eq 0 ]; then
    echo "Command successful"
else
    echo "Command failed with exit code $exit_code"
fi
return "$exit_code"

但是,您可以使用另一个全局变量来存储代码。

相关问题