https://www.cnblogs.com/matthewma/p/6995479.html
需求描述:
在写shell脚本的过程中,用到了if else的写法,突然有多个参数需要判断
那么就想到了if else if的用法,于是进行如下的测试。
测试过程:
1.写如下的测试脚本,进行多个值的判断
复制代码
#!/bin/bash
if [[ $1 = ‘tomcat’ ]];
then
echo “Input is tomcat”
else if [[ $1 = ‘redis’ ]] || [[ $1 = ‘zookeeper’ ]];
then
echo “Input is $1”
else
echo “Input Is Error.”
fi
复制代码
2.执行脚本,看脚本是否正常执行
[oracle@standby ~]$ ./ts01.sh zookeeper
./ts01.sh: line 12: syntax error: unexpected end of file
备注:发现执行是错误的,经过查看可以知道,shell脚本中不是else if而是elif这个写法
3.修改脚本
复制代码
#!/bin/bash
if [[ $1 = ‘tomcat’ ]];
then
echo “Input is tomcat”
elif [[ $1 = ‘redis’ ]] || [[ $1 = ‘zookeeper’ ]];
then
echo “Input is $1”
else
echo “Input Is Error.”
fi
复制代码
4.再次执行修改过的脚本
复制代码
[oracle@standby ~]$ ./ts01.sh zookeeper
Input is zookeeper
[oracle@standby ~]$ ./ts01.sh tomcat
Input is tomcat
[oracle@standby ~]$ ./ts01.sh redis
Input is redis
[oracle@standby ~]$ ./ts01.sh mysql
Input Is Error.
复制代码
备注:脚本执行正常,正确的输出了需要的结果。
shell脚本中else if的正确使用方法:
复制代码
if condition;
then
commands;
elif condition;then
commands;
else
commands;
fi
复制代码