通常的想法是运行命令,然后使用$? 获取退出代码。但是,有时您有多种情况需要获取退出代码。例如,您可能需要隐藏其输出,但仍返回退出代码,或者同时打印退出代码和输出。
ec() { [[ "$1" == "-h" ]] && { shift && eval $* > /dev/null 2>&1; ec=$?; echo $ec; } || eval $*; ec=$?; }
这将使您可以选择禁止输出您想要退出代码的命令。当命令的输出被抑制时,退出代码将直接由函数返回。
我个人喜欢把这个函数放在我的.bashrc file中。
下面我将展示一些你可以使用它的方法:
# In this example, the output for the command will be
# normally displayed, and the exit code will be stored
# in the variable $ec.
$ ec echo test
test
$ echo $ec
0
# In this example, the exit code is output
# and the output of the command passed
# to the `ec` function is suppressed.
$ echo "Exit Code: $(ec -h echo test)"
Exit Code: 0
# In this example, the output of the command
# passed to the `ec` function is suppressed
# and the exit code is stored in `$ec`
$ ec -h echo test
$ echo $ec
0
使用此函数解决您的代码
#!/bin/bash
if [[ "$(ec -h 'ls -l | grep p')" != "0" ]]; then
echo "Error when executing command: 'grep p' [$ec]"
exit $ec;
fi
您还应该注意,您将看到的退出代码将针对正在运行的grep 命令,因为它是最后一个正在执行的命令。不是ls。