我使用过的Linux命令之if - Bash中的条件判断语句
我使用过的Linux命令之if - Bash中的条件判断语句
本文链接: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
使用示例示例一?
[root@jfht ~]# if [ "foo" = "foo" ]; then
示例二
>???? echo expression evaluated as true
> fi
expression evaluated as true
[root@jfht ~]#?
[root@jfht ~]# if [ "foo" = "foo" ]; then
示例三
>???? echo expression evaluated as true
> else
>???? echo expression evaluated as false
> fi
expression evaluated as true
[root@jfht ~]#?
[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
?
[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]#?
示例五 判断文件中是否包含某个字符串echo 1 >file1echo 2 >file2if ! diff -q file1 file2; then echo file1 file2 diffelse echo file1 file2 samefi?
[root@jfht ~]# echo 1 >file1
问题思考
[root@jfht ~]# echo 2 >file2
[root@jfht ~]# if ! diff -q file1 file2; then
>???? echo file1 file2 diff
> else
>???? echo file1 file2 same
> fi
Files file1 and file2 differ
file1 file2 diff
[root@jfht ~]#1. 怎么判断字符串非空?
2. 怎么判断文件非空?
3. 怎么判断文件可执行?
4. 怎么判断目录?
5. 怎么判断数值大小判断?
相关资料【1】BASH Programming 6.1 Dry Theory
【2】刘 泰山的博客 bash if 条件判断
?
返回 我使用过的Linux命令系列总目录
?
1 楼 zhangziqiu 2012-04-01 文章是原创吗? 无意中发现了博主的博客, 如获至宝. 我花了好多时间学习shell, 发现看1个小时的man, 不如看楼主一篇博客清晰! 2 楼 codingstandards 2012-04-04 zhangziqiu 写道文章是原创吗? 无意中发现了博主的博客, 如获至宝. 我花了好多时间学习shell, 发现看1个小时的man, 不如看楼主一篇博客清晰!
确实是原创,每篇平均花费我一到三个小时,包括总结个人使用的经验、阅读英文man手册、以及搜索网络上比较经典的用法。