日期:2014-05-16 浏览次数:20635 次
本文链接:http://codingstandards.iteye.com/blog/780156 ?? (转载请注明出处)
Shell中的条件判断语句,与其他编程语言类似。
如果需要知道有哪些条件判断方式,通过man test就可以得到帮助。
if 条件; then
??? 语句
fi
if 条件; then
??? 语句
else
??? 语句
fi
if 条件; then
??? 语句
elif 条件; then
??? 语句
fi
if 条件; then
??? 语句
elif 条件; then
??? 语句
else
??? 语句
fi
if [ "foo" = "foo" ]; then echo expression evaluated as true fi
?
[root@jfht ~]# if [ "foo" = "foo" ]; then
>???? echo expression evaluated as true
> fi
expression evaluated as true
[root@jfht ~]#
if [ "foo" = "foo" ]; then echo expression evaluated as true else echo expression evaluated as false fi
?
[root@jfht ~]# if [ "foo" = "foo" ]; then
>???? echo expression evaluated as true
> else
>???? echo expression evaluated as false
> fi
expression evaluated as true
[root@jfht ~]#
T1="foo" T2="bar" if [ "$T1" = "$T2" ]; then echo expression evaluated as true else echo expression evaluated as false fi
?
[root@jfht ~]# T1="foo"
[root@jfht ~]# T2="bar"
[root@jfht ~]# if [ "$T1" = "$T2" ]; then
>???? echo expression evaluated as true
> else
>???? echo expression evaluated as false
> fi
expression evaluated as false
[root@jfht ~]#
文件 if_4.sh
#!/bin/sh if [ "$#" != "1" ]; then echo "usage: $0 <file>" exit 1 fi
?
[root@smsgw root]# cat if_4.sh
#!/bin/sh
if [ "$#" != "1" ]; then
??? echo "usage: $0 <file>"
??? exit 1
fi
[root@smsgw root]# chmod +x if_4.sh
[root@smsgw root]# ./if_4.sh
usage: ./if_4.sh <file>
[root@smsgw root]# ./if_4.sh hello
[root@smsgw root]#
?
if grep -q root /etc/passwd; then echo account root exists else echo account root not exist fi
?
[root@jfht ~]# if grep -q root /etc/passwd; then
>???? echo account root exists
> else
>???? echo account root not exist
> fi
account root exists
[root@jfht ~]#
?
if [ -e myfile ]; then echo myfile exists else touch myfile echo myfile created fi
?
[root@jfht ~]# if [ -e myfile ]; then
>???? echo myfile exists
> else
>???? touch myfile