我想检查一下以确保有一些命令可用。如果不是,我想打印一条错误消息然后退出。
我想在不检查变量的情况下执行此操作,因为它是脚本中的一个小点,我不希望它散布在一堆行上。
我想使用的形状基本上是这样的:
rsync --help >> /dev/null 2>&1 || printf "%s\n" "rsync not found, exiting."; exit 1
Run Code Online (Sandbox Code Playgroud)
不幸的是,exit 1
不管 rsync 结果如何,都会执行。
有没有办法在 bash 中使用这个 perl 类型的 die 消息,或者没有?
Jef*_*ler 13
为了直接回答问题,大括号将命令组合在一起,因此:
rsync --help >> /dev/null 2>&1 || { printf "%s\n" "rsync not found, exiting."; exit 1; }
Run Code Online (Sandbox Code Playgroud)
作为做你想做的事情的建议,但以另一种方式:
#!/usr/bin/env bash
for c in rsync ls doesnotexist othercommand grep
do
if ! type "$c" &> /dev/null
then
printf "$c not found, exiting\n"
exit 1
fi
done
Run Code Online (Sandbox Code Playgroud)
如果你想die
在 shell 中模拟 perl :
function die {
printf "%s\n" "$@" >&2
exit 1
}
# ...
if ! type "$c" &> /dev/null
then
die "$c not found, exiting"
fi
# ...
Run Code Online (Sandbox Code Playgroud)
一定要单线吗?我不是短路的忠实粉丝。我会这样写:
if ! rsync --help &>/dev/null; then
printf "%s\n" "rsync not found, exiting."
exit 1
fi
Run Code Online (Sandbox Code Playgroud)