14.1.2 文件测试
本章开头提到的“测试文件是否存在”就是“文件测试”的一种典型需求。Shell中提供了大量的文件测试符,其格式如下:
- #
- 文件测试方法一
- test file_operator FILE
- #
- 文件测试方法二
- [ file_operator FILE ]
其中file_operator是文件测试符(具体参考表14-1),FILE是文件、目录(可以是文件或目录的全路径)。
同样以判断文件varlog/message为例,使用文件测试的方法测试该文件“是否存在”,只需要使用-e操作符即可。
- #
- 测试一个存在的文件则$?
- 返回0
- [root@localhost ]# test -e varlog/messages
- [root@localhost ]# echo $?
- 0
- #
- 测试一个不存在的文件$?
- 返回值不为0
- [root@localhost ]# test -e varlog/messages01
- [root@localhost ]# echo $?
- 1
- #
- 用[]
- 测试
- [root@localhost ]# [ -e varlog/messages ]
- [root@localhost ]# echo $?
- 0
- [root@localhost ]# [ -e varlog/messages01 ]
- [root@localhost ]# echo $?
- 1
表14-1罗列了Shell中的所有文件比较符,它们的使用方法可参照之前的例子,只需参考表格中的“文件测试”部分改变相应的文件操作符即可。
表14-1 文件测试符
这里针对表14-1中最后两行内容——文件新旧的比较做一些说明。FILE1-nt FILE2中的-nt是newer than的意思,而FILE1-ot FILE2中的ot是older than的意思。文件新旧比较的主要使用场景是判断文件是否被更新或增量备份时,用于判断一段时间以来更新过的文件。
以下是参考表14-1写出的测试某个文件的读、写、执行属性的代码。
- [root@localhost ~]# cat rwx.sh
- #!/bin/bash
- read -p "What file do you want to test?" filename
- if [ ! -e "$filename" ]; then
- echo "The file does not exist."
- exit 1
- fi
- if [ -r "$filename" ]; then
- echo "$filename is readable."
- fi
- if [ -w "$filename" ]; then
- echo "$filename is writeable"
- fi
- if [ -x "$filename" ]; then
- echo "$filename is executable"
- fi