我创建了一个bash脚本,该脚本触及特定安装中的文件,以监视目录锁定或存储问题。我使用多个if语句完成了这个操作,但是如果我在if的末尾使用exit使用以下语法,则退出完整脚本而不继续检查其余的服务器主机。有人可以告诉我,是否有更好的方法可以做到这一点,或者我是否可以替换退出以便脚本继续使用其余的if语句?
ssh $SERVER1 touch /apps/mount/im.alive.txt
if [ $? -ne 0 ]; then
echo "$SERVER1 is in accessible. Please escalate"
else
exit
fi
ssh $SERVER2 touch /apps/mount/im.alive.txt
if [ $? -ne 0 ]; then
echo "$SERVER2 is in accessible. Please escalate"
else
exit
fi
答案 0 :(得分:1)
详细说明@Mighty Portk的评论:else
语句的if
部分不是强制性的,所以你可以在没有它的情况下离开,并且没有exit
:
ssh $SERVER1 touch /apps/mount/im.alive.txt
if [ $? -ne 0 ]; then
echo "$SERVER1 is in accessible. Please escalate"
fi
ssh $SERVER2 touch /apps/mount/im.alive.txt
if [ $? -ne 0 ]; then
echo "$SERVER2 is in accessible. Please escalate"
fi
答案 1 :(得分:0)
或者只是像这样简化:
ssh "$SERVER1" touch /apps/mount/im.alive.txt || \
echo "$SERVER1 is in accessible. Please escalate"
ssh "$SERVER2" touch /apps/mount/im.alive.txt || \
echo "$SERVER2 is in accessible. Please escalate"
或者
for S in "$SERVER1" "$SERVER2"; do
ssh "$S" touch /apps/mount/im.alive.txt || \
echo "$S is in accessible. Please escalate."
done
您也可以将其变成脚本:
#!/bin/sh
for S; do
ssh "$S" touch /apps/mount/im.alive.txt || \
echo "$S is in accessible. Please escalate."
done
用法:
sh script.sh "$SERVER1" "$SERVER2"
答案 2 :(得分:0)
您不必运行“ssh”然后显式测试其退出代码。 “if”命令将为您执行此操作。我就是这样写的:
if ssh $SERVER1 touch /apps/mount/im.alive.txt
then
true # do-nothing command
else
echo "$SERVER1 is in accessible. Please escalate"
fi
if ssh $SERVER2 touch /apps/mount/im.alive.txt
then
true # do-nothing command
else
echo "$SERVER2 is in accessible. Please escalate"
fi
但是,由于您在多个SERVER上执行相同的操作集,因此可以使用循环:
for server in $SERVER1 $SERVER2
do
if ssh $server touch /apps/mount/im.alive.txt
then
true # do-nothing command
else
echo "$server is in accessible. Please escalate"
fi
done
答案 3 :(得分:0)
最后,(在所有好的建议之后),使用函数进行某些操作(例如错误消息等)是一种很好的做法。因此,
#put this at the top of your script
eecho() {
echo "Error: $@" >&2
return 1
}
将作为echo
运行,但始终将错误消息写入STDERR,并返回problem
(非零状态),以便您可以执行下一步:
[[ some_condition ]] || eecho "some error message" || exit 1
e.g。用exit
链接它。 (见konsolebox的推荐)