Shell的条件执行多级的if...elif...else..fi
(2018-08-13 10:16:49)
多级的if...elif...else...fi让脚步有多种可能性和条件。
if TEST-COMMANDS
then
TEST-COMMANDS is zero(true - 0)
execute all
commands up to elif statement
elif TEST-COMMANDS
then
TEST-COMMANDS is zero(true - 0)
execute all
commands up to elif statement
elif TEST-COMMANDS
then
TEST-COMMANDS is zero(true - 0)
execute all
commands up to elif statement
else
None of the
above TEST-COMMANDS are true(i.e. all of the above nonzero or
false) execute all commands up to fi
fi
实例
[root@aa ~]# cat checknumber.sh
#!/bin/bash -
#如果指定的命令行参数个数等于0,则显示必须指定一个参数的提示信息,然后退出脚本,退出状态码为1
if [ $# -eq 0 ]
then
#显示必须指定一个参数的提示信息
echo "$0:
You must give/supply one integers."
#退出脚本,退出状态码为1
exit 1
fi
#如果指定的参数大于0
if [ $1 -gt 0 ]
then
echo "The
number is positive."
#如果指定的参数小于0
elif [ $1 -lt 0 ]
then
echo "The
number is negative."
#如果指定的参数登录0
elif [ $1 -eq 0 ]
then
echo "The
number is 0."
else
echo "Opps!
$1 is not number, give number."
fi
[root@aa ~]# ./checknumber.sh
./checknumber.sh: You must give/supply one integers.
[root@aa ~]# ./checknumber.sh 1
The number is positive.
[root@aa ~]# ./checknumber.sh -1
The number is negative.
[root@aa ~]# ./checknumber.sh 0
The number is 0.
[root@aa ~]# ./checknumber.sh a
Opps! a is not number, give number.
if TEST-COMMANDS
then
elif TEST-COMMANDS
then
elif TEST-COMMANDS
then
else
fi
实例
[root@aa ~]# cat checknumber.sh
#!/bin/bash -
#如果指定的命令行参数个数等于0,则显示必须指定一个参数的提示信息,然后退出脚本,退出状态码为1
if [ $# -eq 0 ]
then
fi
#如果指定的参数大于0
if [ $1 -gt 0 ]
then
#如果指定的参数小于0
elif [ $1 -lt 0 ]
then
#如果指定的参数登录0
elif [ $1 -eq 0 ]
then
else
fi
[root@aa ~]# ./checknumber.sh
./checknumber.sh: You must give/supply one integers.
[root@aa ~]# ./checknumber.sh 1
The number is positive.
[root@aa ~]# ./checknumber.sh -1
The number is negative.
[root@aa ~]# ./checknumber.sh 0
The number is 0.
[root@aa ~]# ./checknumber.sh a
Opps! a is not number, give number.