您的位置:首页 > 运维架构 > Shell

Shell 编程5(条件判断语句if)

2013-03-06 17:53 701 查看
1简单的if结构是:      if  expression
then command command … fi
eg 判断脚本 参数个数是否为0

#!/bin/bash
function usage()
{
echo "must have a param"
echo "usage $0 param"
}

if [ $# = 0 ]
then
usage
exit 1
fi

echo $#
exit 0


eg2 脚本只能由root用户执行

#!/bin/bash

if [ $UID != "0" ]
then
echo "must use root user to execute it . . . . ."
exit 1
fi

echo "you are root , you can execute it!"


运行结果:

anders@anders-virtual-machine:~/code/shell/if$ ./if2.sh
must use root user to execute it . . . . .
anders@anders-virtual-machine:~/code/shell/if$ sudo ./if2.sh
you are root , you can execute it!


2 if else

命令是双向选择语句,当用户执行脚本时如果不满足if后的表达式也会执行else后的命令,所以有很好的交互性。其结构为:

if expression1

then

command



command

else

command



command

fi

eg

#!/bin/bash

if [ -w test ]
then
cat tmp >> test
echo "put tmp file into test file"
rm -r tmp
exit 0
else
echo "test has no write privilege"
exit 1
fi


3 if elif 多条件检测

if expression1

then

command

command



elif expression2

then

command

command



elif expressionN

then

command



command

else

command



command

fi

#!/bin/bash
function usage()
{
echo "error must have a param"
echo "usage $0 filename"
}

if [ $# = 0 ]
then
usage
exit 1
fi

if [ -d $1 ]
then
echo -n "Sure you want to delete the directory?[yes | no]"
read ANS
if [ $ANS = "yes"]
then
rm -rf $1 &>/dev/null
exit 0
elif [ $ANS = "no" ]
then
exit 0
else
echo "input error!"
exit
fi
else
echo -n "Sure you want to delete the file?[yes|no]"
read ANS
if [ $ANS = "yes" ]
then
rm -rf $1 &>/dev/null
fi
fi


4 case 多条件判断语句

和if/elif/else结构一样,case结构同样可用于多分支选择语句,常用来根据表达式的值选择要执行的语句,该命令的一般格式为:

caseVariable in

value1)

command



command;;

value2)

command



command;;



valueN)

command



command;;

*)

command



command;;

esac

#!/bin/bash
echo "enter today:"
read today

case $today in
monday)
echo "1"
;;
sunday)
echo "2"
;;
friday)
echo "3"
;;
esac
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: