shell/if_test/ target=_blank class=infotextkey>shell条件判断
在shell语句中,条件判断语句分为三种:
shell if语句条件判断、case语句条件判断,以及test条件判断语句。
而其中,shell if语句是用的最多的一种条件判断,它又分为单层条件判断、多层条件判断两种。
一、shell单层、简单条件判断式
如果只有一个判断式要进行,可以这样:
if [ 条件判断式 ]; then
当条件判断式成立时,可以进行的命令工作内容;
fi <==将 if 反过来写,就成为 fi 啦!结束 if 之意!
例子:
[root@www scripts]# cp sh06.sh sh06-2.sh <==用改的比较快!
[root@www scripts]# vi sh06-2.sh
#!/bin/bash
# Program:
# This program shows the user's choice
# History:
# 2005/08/25 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
read -p "Please input (Y/N): " yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
echo "OK, continue"
exit 0
fi
if [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
echo "Oh, interrupt!"
exit 0
fi
echo "I don't know what your choice is" && exit 0
二、shell多重、复杂条件判断式
简单语法:
复杂情况,使用如下语法:
例子:
[root@www scripts]# cp sh06-2.sh sh06-3.sh
[root@www scripts]# vi sh06-3.sh
#!/bin/bash
# Program:
# This program shows the user's choice
# History:
# 2005/08/25 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
read -p "Please input (Y/N): " yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
echo "OK, continue"
elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
echo "Oh, interrupt!"
else
echo "I don't know what your choice is"
fi
利用 case ..... esac 判断
语法:
case $变量名称 in <==关键字为 case ,还有变量前有钱字号
"第一个变量内容") <==每个变量内容建议用双引号括起来,关键字则为小括号 )
程序段
;; <==每个类别结尾使用两个连续的分号来处理!
"第二个变量内容")
程序段
;;
*) <==最后一个变量内容都会用 * 来代表所有其他值
不包含第一个变量内容与第二个变量内容的其他程序运行段
exit 1
;;
esac <==最终的 case 结尾!『反过来写』思考一下!
例子:
[root@www scripts]# vi sh09-2.sh
#!/bin/bash
# Program:
# Show "Hello" from $1.... by using case .... esac
# History:
# 2005/08/29 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
case $1 in
"hello")
echo "Hello, how are you ?"
;;
"")
echo "You MUST input parameters, ex> {$0 someword}"
;;
*) # 其实就相当於万用字节,0~无穷多个任意字节之意!
echo "Usage $0 {hello}"
;;
esac