Bash 如何使用多个if语句
我已经创建了一个bash脚本,它在特定装载中接触一个文件,以监视目录锁或存储问题。我已经使用多个if语句完成了这项工作,但是如果我在if结尾使用下面的语法exit,那么这将退出整个脚本,而不会继续检查其余的服务器主机。有人能告诉我是否有更好的方法,或者我是否可以替换退出,以便脚本继续使用其余的if语句吗Bash 如何使用多个if语句,bash,if-statement,Bash,If Statement,我已经创建了一个bash脚本,它在特定装载中接触一个文件,以监视目录锁或存储问题。我已经使用多个if语句完成了这项工作,但是如果我在if结尾使用下面的语法exit,那么这将退出整个脚本,而不会继续检查其余的服务器主机。有人能告诉我是否有更好的方法,或者我是否可以替换退出,以便脚本继续使用其余的if语句吗 ssh $SERVER1 touch /apps/mount/im.alive.txt if [ $? -ne 0 ]; then echo "$SERVER1 is in accessible
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
要详细说明@Mighty Portk的评论:
if
语句的else
部分不是强制性的,因此您可以不用它,也不用退出:
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
或者简单地说:
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"
或
您还可以将其转换为脚本:
#!/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"
您不必运行“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
但是,由于您在多台服务器上执行同一组操作,因此可以使用循环:
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
最后,(在所有好的建议之后)将函数用于某些操作(如错误消息等)是一个很好的实践。因此,
#put this at the top of your script
eecho() {
echo "Error: $@" >&2
return 1
}
将作为回显
,但始终将错误消息写入STDERR,并返回问题
(非零状态),以便您可以执行下一步操作:
[[ some_condition ]] || eecho "some error message" || exit 1
e、 g.用退出
链接它。(参见konsolebox的建议)顺便说一句,它是“不可访问的”,而不是“可访问的”,谢谢。我认为循环是一个好主意,因为我至少在6台服务器上这样做。我是否只提供for中的主机列表?i、 e.对于$SERVER1$SERVER2$SERVER3等中的服务器?
[[ some_condition ]] || eecho "some error message" || exit 1