我希望能够将命令组合在一起,这样如果一组命令中的一个命令失败,则执行另一个命令,即
$ ping 1; echo 1 || echo 2
将返回等效的
$ ping 1; echo 2
结果
connect: Invalid argument
2
即。前两个命令ping 1
和echo 1
应该组合在一起,这样如果其中一个命令失败,第三个echo 2
将被执行。
我尝试过的事情,
$ (ping 1; echo 1) || echo 2
$ (( ping 1; echo 1 )) || echo 2
$ [[ ping 1; echo 1 )) || echo 2
$ { ping 1; echo 1; } || echo 2
$ eval "ping 1; echo 1" || echo 2
$ function try_ping { ping 1; echo 1; }; try_ping || echo 2
编辑我仍然需要运行第一组中的所有命令,因此&&
对我不起作用。
例如,
function my_ping {
local exit=0
command1
exit=$(( exit + $? ))
command2
exit=$(( exit + $? ))
if [[ "$exit" -ne "0" ]]; then
command3
fi
}
答案 0 :(得分:2)
darby@darbycrash:~$ ping 1 2>/dev/null && echo 1 || echo 2
2
darby@darbycrash:~$
你可以使用&&对于一起运行命令,如果一个失败,链就会被破坏。 这是你的例子,但已修复。 享受。
P.S。我已将错误消息重定向为null。
修改后更新
此脚本运行第一组的所有命令,如果有人在没有退出代码的情况下退出,则设置一个变量,使用if运行第二组或提醒您不需要更多运行任何内容:
#!/bin/bash
function check () {
$1 >/dev/null 2>&1
echo $?
}
command=("curl -sSL google.com" "echo 1" 'ping localhost -c 1' 'ls' 'false')
for ((i=0;i<${#command[@]};i++)); do
echo "Command \"${command[$i]}\" returned value $(check "${command[$i]}")"
if (($(check "${command[$i]}") != 0)); then second=1; fi
done
if ((second == 1)); then
echo "I must run second group of commands because something have not worked!"
echo 2
else
echo "All is gone without issues! Goodbye $USER!"
exit 0
fi
<强>输出强>
darby@Debian:~/Scrivania$ bash ex
Command "curl -sSL google.com" returned value 0
Command "echo 1" returned value 0
Command "ping localhost -c 1" returned value 0
Command "ls" returned value 0
Command "false" returned value 1
I must run second group of commands because something have not worked!
2
darby@Debian:~/Scrivania$ bash ex
Command "curl -sSL google.com" returned value 0
Command "echo 1" returned value 0
Command "ping localhost -c 1" returned value 0
Command "ls" returned value 0
Command "true" returned value 0 # I have changed false to true in the command array
All is gone without issues! Goodbye darby!
darby@Debian:~/Scrivania$
答案 1 :(得分:1)
这个怎么样?
OK=1
ping 1 || OK=0
echo 1 || OK=0
[[ "$OK" == "0" ]] && echo 2
答案 2 :(得分:0)
示例:
ls && tree && echo success || echo epic fail
如果命令ls
或tree
失败,则“史诗般失败”#39;会被打印出来。