Shell 编程5(条件判断语句if)
2013-03-06 17:53
701 查看
1简单的if结构是: if expression
then command command … fi
eg 判断脚本 参数个数是否为0
eg2 脚本只能由root用户执行
运行结果:
2 if else
命令是双向选择语句,当用户执行脚本时如果不满足if后的表达式也会执行else后的命令,所以有很好的交互性。其结构为:
if expression1
then
command
…
command
else
command
…
command
fi
eg
3 if elif 多条件检测
if expression1
then
command
command
…
elif expression2
then
command
command
…
elif expressionN
then
command
…
command
else
command
…
command
fi
4 case 多条件判断语句
和if/elif/else结构一样,case结构同样可用于多分支选择语句,常用来根据表达式的值选择要执行的语句,该命令的一般格式为:
caseVariable in
value1)
command
…
command;;
value2)
command
…
command;;
…
valueN)
command
…
command;;
*)
command
…
command;;
esac
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
相关文章推荐
- shell脚本编程:条件判断if语句使用小结
- shell 编程if条件判断与if 真假判断
- Shell中的条件判断语句if~then~fi
- bash编程之条件判断,if语句!
- linux之基础shell脚本编程2 if语句循环判断
- shell基础之二:条件判断语句if、case及read命令,
- shell 编程中使用到得if语句内判断参数
- Shell脚本编程---条件判断if
- Linux脚本(shell)编程(五) if 条件判断
- shell 编程中使用到得if语句内判断参数
- shell 编程中使用到得if语句内判断参数
- shell 编程中使用到得if语句内判断参数
- Shell编程之IF条件语句各种案例演练
- 25_Shell语言――――if条件判断之组合判断(与、或、非)和多分支if语句
- shell脚本编程中条件判断语句中各个参数的含义
- Linux之shell编程条件判断-if,while,for,case
- shell 编程中使用到得if语句内判断参数
- Nginx中if语句中的判断条件
- Shell中条件判断if中的各种参数的意思
- 求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)