首页 >> 大全

shellScript学习02--判断指令test和[]

2023-08-26 大全 30 作者:考证青年

test1.test指令的用处

用来检测某些某些档案是否存在相关的属性。如:是否有操作权限,文件是否存在等。

2.用法

1.判断某个目录是否存在

test -e /xie

2.判断某个目录是否存在,存在则输出yes,否则输出no

test -e /xie && echo "yes" || echo "no"

3.相关参数

test -e

-e 是否存在

-f 是否为文件

-d 是否为目录

test -r 权限的判断

-r 是否有读的权限 -w 是否有写的权限 -x 是否可执行

test file1 -nt file2 两个文件之间的判断

-nt (newer than)判断 file1 是否比 file2 新

-ot (older than)判断 file1 是否比 file2 旧

-ef 判断 file2 与 file2 是否为同一档案

test n1 -eq n2 两个整数之间的判断

-eq 两数值相等 (equal) -ne 两数值不等 (not equal)

-gt n1 大于 n2 ( than) &bnsp;-lt n1 小于 n2 (less than)

-ge n1 大于等于 n2 ( than or equal) -le n1 小于等于 n2 (less than or equal)

判断字符串的数据

test -z 判定字符串是否为 0 ?若 为空字符串,则为 true

test -n 判定字符串是否非为 0 ?若 为空字符串,则为 false。 注: -n 亦可省略

test str1 = str2 判定 str1 是否等于 str2 ,若相等,则回传 true

test str1 != str2 判定 str1 是否不等于 str2 ,若相等,则回传 false

多重条件判定,例如: test -r -a -x

-a (and)两状况同时成立!例如 test -r file -a -x file,则 file 同时具有 r 与 x 权限时,才回传 true。

-o (or)两状况任何一个成立!例如 test -r file -o -x file,则file 具有 r 或 x 权限时,就可回传 true。

! 反相状态,如 test ! -x file ,当 file 不具有 x 时,回传 true

3.案例

判断一下, 让使用者输入一个档名,我们判断:

1. 这个档案是否存在,若不存在则给予一个『the file does not exist』的讯息,并中断程序;

2. 若这个档案存在,则判断他是个档案或目录,结果输出『 file』或 『』

3. 判断一下,执行者的身份对这个档案或目录所拥有的权限,并输出权限数据!

这里写图片描述

.sh


#!/bin/bash
#test命令的使用
#xie
#2018年5月17
read -p "please input fileName:" fileName
#判断用户是否有输入内容
test -z $fileName && echo "you must input a fileName!" && exit 0#判断档案是否存在
test ! -e $fileName && echo "the file does not exist" && exit 0#判断它的属性
test -f $fileName && fileType="regular file"
test -d $fileName && fileType="directory"
test -r $fileName && perm="read"
test -w $fileName && perm="$perm write"
test -x $fileName && perm="$perm execute"#输出结果信息
echo -e "$fileName is a $fileType"
echo -e "$fileName have $perm permission \n"

[]1.用处

判断符号[ ] 可以用来来进行数据的判断

2.用法

判断变量是否为空的,可以这样做:

[ -e $xie ]

中括号的使用方法与标志与 test 几乎一模一样

注意:

在中括号 [] 内的每个组件都需要有空格键来分隔;如 [和-e之间有空格,-e和$xie之间有空格

. 在中括号内的变量,最好都以双引号来设定;

. 在中括号内的常数,最好都以单或双引号来设定。

案例 当执行一个程序的时候,这个程序会让使用者选择 Y 或 N ,如果使用者输入 Y 或 y 时,就显示『 yes,you are pig 』如果使用者输入 n 或 N 时,就显示『 you not a man』如果不是 Y/y/N/n 之内的其它字符,就显示『you are pig,what you type?!』

这里写图片描述

#!/bin/bash
#用户输入y继续,n结束,其他输出不知道
#xie
#2018年5月17日14:11:03
read -p "are you a pig? y/n :" choice
[ $choice == "y" -o $choice == "Y" ] && echo "yes,you are pig" && exit 0
[ $choice == "n" -o $choice == "N" ] && echo "you not a man" && exit 0
echo "you are pig,what you type?!" && exit 0

参考文献:鸟哥的linux私房菜

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了