linux - 如何在 shell 脚本中获取最后一个 Bash shell 命令的成功状态?

标签 linux bash shell error-handling

有时我经常连续调用两个命令。然而,第二个命令只有在第一个命令成功的情况下才有意义。

我想做这样的事情:

#!/bin/bash

if [ $? -gt 0 ]
then
    echo "WARNING: previous command entered at the shell prompt failed"
fi

但它不起作用:

t@quad:~$ echo "abc" | grep def
t@quad:~$ ./warnme.sh 
Last command succeeded

我想要的是这样的:

t@quad:~$ echo "abc" | grep def
t@quad:~$ echo ${PIPESTATUS[1]}
1

我们可以清楚地看到最后一个命令失败了。

我想要的结果:

t@quad:~$ echo "abc" | grep def
t@quad:~$ ./warnme.sh 
WARNING: previous command entered at the shell prompt failed

我找不到办法。

最佳答案

command1 && command2

完全按照您的意愿行事:仅当命令 1 成功时,命令 2 才会执行。例如你可以这样做:

ls a.out && ./a.out

然后 a.out 只有在可以列出时才会执行。我在 http://www.linuxintro.org/wiki/%26%26 上写了关于这个的维基博客。

关于linux - 如何在 shell 脚本中获取最后一个 Bash shell 命令的成功状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21467624/

相关文章:

linux - Bash 和对话框 UI,如何动态改变颜色

linux - 在 *nix cd 命令中将目录更改为最后一个匹配项

windows - Erlang shell 自动完成功能在 Windows 上不起作用

shell - 使: referencing shell variables in sed call

mysql - apache进程和Mysql进程过载

linux - 如何获得永久MAC地址

linux - 为什么是 `read line; declare $line` 和 `find ... +` ?

linux - 在 ssh 中使用参数运行多个命令

c - 溢出的缓冲区数据不会连续存储

linux - Git中如何处理多个Linux用户文件