一、常见的文件测试操作符
-a/-e
文件
文件是否存在
-b
文件
文件是否存在,且为块文件,如果文件存在且是一个块文件,则结果为 0
-c
文件
文件是否存在且为字符文件,如果文件存在且是一个字符文件,则结果为 0
-L
文件
文件存在且为链接文件则为真
-d
文件
文件存在且为目录则为真,即测试表达式成立
-f
文件
文件存在且为普通文件则为真,即测试表达式成立
-s
文件
文件存在且文件大小不为 0 则为真
-u
文件
文件是否设置 suid 位,如果设置了 suid ,则结果为 0
-r
文件
文件存在且可读为真
-w
文件
文件存在且可写为真
-x
文件
文件存在且可执行则为真
f1 -nt f2
,
nt
为
newer
than
文件 f1 比文件 f2 新则为真,根据文件的修改时间来计算
f1 -ot f2
,
ot
为
older
than
文件 f1 比文件 f2 旧则为真,根据文件的修改时间来计算
二、条件测试
test
语法1: test <测试 表达式>test命令和 < 测试表达式 >之间至少有一个空格
[]
语法 2 : [ < 测试表 达式> ]该方法和 test 命令的用法一样, [] 的边界和内容之间至少有一个空格
注意:[] 与测试内容之间存在空格
[[]]
语法 3 : [[ < 测试 表达式> ]]比 test 和 [] 更新的语法格式。 [[]] 的边界和内容之间至少有一个空格。 [[]] 中可以使用通配符等进行模式匹配
(())
语法 4:((< 测试表达 式>))一般用于 if 语句里,双小括号两端不需要有空格,测试对象只能是整数
注意:如果测试的文件路径是用变量来代替,变量一定要加引号
三、练习
练习
1
:让用户输入一个文件名,并做如下判断:
(1)如果用户输入的文件为空时显示:
you must input a filename
,并中断程序;
(2)如果用户输入的文件不存在时,显示
the file do not exist
,并中断程序;
(3)如果文件存在,判断该文件的文件类型和执行者对该文件所拥有的的权限。
说明:由于
root
在很多权限的限制上面都是无效的,所以使用
root
执行这个脚本时,常常会发现与
ls -l
的
结果不相同。所以建议使用一般用户来执行这个脚本。
#!/bin/bash
#########################
#File name:2.sh
#Version:v1.0
#Email:admin@test.com
#Created time:2022-08-27 02:23:25
#Description:
########################
read -p "input a filename:" filename
test -z $filename && echo "you must input a filename" && exit 0
test ! -e $filename && echo "the file $filename do not exit" && exit 0
test -f $filename && filetype="regulare file"
test -d $filename && filetype="directory"
test -r $filename && perm="readable"
test -w $filename && perm="writeable"
test -x $filename && perm="executable"
echo "the $filename is a $filetype"
echo "and the permissons are: $perm"