九鼎创展论坛中文版English
登录 | 立即注册 设为首页收藏本站 切换到宽版
查看: 4074|回复: 0
打印 上一主题 下一主题

shell 脚本学习之判断条件

[复制链接]
跳转到指定楼层
楼主
发表于 2011-11-24 10:12:10 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

在之前的shell语言学习笔记中已经写过shell的几种判断语句及循环语句,也简单的介绍了shell语言判断语句和判断条件。在此再做进一步学习。

test命令的测试功能

test命令用于检测系统文件及其相关属性,如检查某文件是否存在,检查某文件的权限等。判断当前目录下是否存在某文件study可以用以下命令:

1 #test -e study

-e 选项是测试某文件是否存在(包括文件和文件夹),该执行结果不会输出任何信息,但是我们可以通过&&及||来改写使其展现相关信息,改写后的命令如下:

1 #test -e study && echo "exist!" || echo "not exist!"

该命令的作用就是当study文件存在时就输出字符串”exist!”,当不存在时就输出字符串”not exist!”

以下是test命令常用的测试标志:

1. 某文件名的类型检测(存在与否及文件类型)(test -e filename)

-e :该“文件名”是否存在。
-d :该文件名是否为目录。
-f  :该文件名是否为普通文件。
b,c,S,p,L分别指的是块设备、字符设备、套接字文件、管道文件及链接文件。

2. 文件权限的检测(test -r filename)

-r :该文件是否具有可读属性
-w :该文件是否具有可写属性
-x :该文件是否具有可执行属性
-s  :该文件是否为非空白文件

3. 比较两个文件(test file_a nt file_b)

-nt :文件file_a是否比file_b新
-ot :文件file_a是否比file_b旧
-ef :判断两个文件是否为同一文件,可用于判断硬连接。(主要判断两个文件是否均指向同一个inode)

4. 两个整数之间的判断(test n1 -eq n2)

-eq :两个数相等(equal)
-ne :两个数不相等(not equal)
-gt :前者大于后者(greater than)
-lt :前者小于后者(less than)
-ge :前者大于等后者
-le :前者小于等于后者

5. 判断字符串

test -z str :判断字符串是否为空,若为空则回传true
test -n str :判断字符串是否为非空,左路为非空则回传true(-n亦可省略)
test str_a = str_b及test str_a != str_b:判断两字条串是否相等及不相等。

6. 多重判断条件(test -r file -a -w file)

-a :and,当两个条件都满足时才回传true,即file具有读和写权限
-o : or,当两个条件满足其一时即回传true
-! :条件求反,test -! -x file,即当file不具有执行权限时才回传true

下面是两个简单的shell脚本,判断其功能:

1 2 3 4 #!/bin/bash echo "lease input a filename:" read -e  filename (test -e $filename && (test -d $filename && echo "directory" ||( test -f $filename && echo "regular")) )||echo "$filename does not exist"

1 2 3 4 5 6 7 8 9 10 11 12 #!/bin/bash echo -e "The program will show you that filename is exist which input by you." read -p "Input a filename:" filename test -z $filename && echo "You must input a filename." && exit 0 test ! -e $filename && echo "The filename $filename DO NOT exist" && exit 0 test -f $filename && filetype="Regulare file" test -d $filename && filetype="directory"; test -r $filename && perm="readable" test -w $filename && perm="$perm writable" test -x $filename && perm="$perm executable" echo "The filenamefilename is a $filetype" echo "And the permission areperm"

使用判断符号[ ]

可以使用判断符号进行数据的判断,如检查某变量是否为空 [ -z $SHELL ],需要注意的是中括号(“[]”)内的组件必须以空格隔开。有以下脚本:

1 2 3 4 5 #!/bin/bash read -p "input you choice:" choice [ "$choice" == "y" ] || [ "$choice" == "Y" ] && echo "OK,continue" && exit 0 [ "$choice" == "n" ] || [ "$choice" == "N" ] && echo "Oh,interrupt!" && exit 0 echo "I don't know what is your choice" && exit 0

注:这些内容是参考的《鸟哥的Linux私房菜》一书中的部分章节。


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|深圳市九鼎创展科技官方论坛 ( 粤ICP备11028681号-2  

GMT+8, 2024-5-27 17:22 , Processed in 0.019580 second(s), 17 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表