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

test

1.test指令的用处

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

2.用法

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

test -e /xie

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

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

3.相关参数
test -e filename
-e 是否存在
-f 是否为文件
-d 是否为目录
test -r filename 权限的判断
-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 (greater than) &bnsp;-lt n1 小于 n2 (less than)
-ge n1 大于等于 n2 (greater than or equal) -le n1 小于等于 n2 (less than or equal)
判断字符串的数据
test -z string 判定字符串是否为 0 ?若 string 为空字符串,则为 true
test -n string 判定字符串是否非为 0 ?若 string 为空字符串,则为 false。 注: -n 亦可省略
test str1 = str2 判定 str1 是否等于 str2 ,若相等,则回传 true
test str1 != str2 判定 str1 是否不等于 str2 ,若相等,则回传 false
多重条件判定,例如: test -r filename -a -x filename
-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.shellScript案例

判断一下, 让使用者输入一个档名,我们判断:
1. 这个档案是否存在,若不存在则给予一个『the file does not exist』的讯息,并中断程序;
2. 若这个档案存在,则判断他是个档案或目录,结果输出『regular file』或 『directory』
3. 判断一下,执行者的身份对这个档案或目录所拥有的权限,并输出权限数据!
这里写图片描述

testCommand.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之间有空格
. 在中括号内的变量,最好都以双引号来设定;
. 在中括号内的常数,最好都以单或双引号来设定。

shellScript案例

  1. 当执行一个程序的时候,这个程序会让使用者选择 Y 或 N ,
  2. 如果使用者输入 Y 或 y 时,就显示『 yes,you are pig 』
  3. 如果使用者输入 n 或 N 时,就显示『 you not a man』
  4. 如果不是 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私房菜

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值