除了测试字符串和算术式,用户还经常需要测试文件(或目录)的状态,下表列出了文件测试的常用选项。
选项 | 作用 |
---|---|
-e File | 如果文件File存在(Exist),则为True |
-s File | 如果文件File存在且文件大小(Size)大于零,则为True |
-f File | 如果文件File存在且是普通文件(File),则为True |
-d File | 如果文件File存在且是目录(Directory),则为True |
-b File | 如果文件File存在且是块(Block)特殊文件,则为True |
-c File | 如果文件File存在且是字符(Character)特殊文件,则为True |
-L File | 如果文件File存在且是符号链接(Link)文件,则为True |
-r File | 如果文件File存在且是可读的(Readable),则为True |
-w File | 如果文件File存在且是可写的(Writable),则为True |
-x File | 如果文件File存在且是可执行的(Executable),则为True |
-O File | 如果文件File存在且属于当前用户(Owner),则为True |
-G File | 如果文件File存在且属于当前用户组(Group),则为True |
File1 -nt File2 | 如果文件File1新于(Newer Then) File2,则为True |
File2 -ot File2 | 如果文件File1旧于(Older Then) File2,则为True |
例如:
#!/bin/bash
echo -n "Please input the file name:"
read filename
if [ ! -e $filename ]
then
echo "File"${$filename}"not exist."
exit
fi
if [ -f $filename ]
then
echo "File "${filename}" is an ordinary file."
elif [ -d $filename ]
then
echo "File "${filename}" is a directory file."
else
echo "File "${filename}" is neither an ordinary file nor a directory file."
fi
上述shell脚本解释:
- 脚本接收用户输入的文件名后,判断该文件是否存在。如果不存在,则输出错误信息并结束。
- 如果存在,判断是普通文件还是目录文件,输出相应信息,如果既不是普通文件也不是目录文件,则执行else后面的语句输入相应信息。
- 符号"!"表示把逻辑值取反。