14.1.2 文件测试

本章开头提到的“测试文件是否存在”就是“文件测试”的一种典型需求。Shell中提供了大量的文件测试符,其格式如下:


  1. #
  2. 文件测试方法一
  3. test file_operator FILE
  4. #
  5. 文件测试方法二
  6. [ file_operator FILE ]

其中file_operator是文件测试符(具体参考表14-1),FILE是文件、目录(可以是文件或目录的全路径)。

同样以判断文件varlog/message为例,使用文件测试的方法测试该文件“是否存在”,只需要使用-e操作符即可。


  1. #
  2. 测试一个存在的文件则$?
  3. 返回0
  4. [root@localhost ]# test -e varlog/messages
  5. [root@localhost ]# echo $?
  6. 0
  7. #
  8. 测试一个不存在的文件$?
  9. 返回值不为0
  10. [root@localhost ]# test -e varlog/messages01
  11. [root@localhost ]# echo $?
  12. 1
  13. #
  14. 用[]
  15. 测试
  16. [root@localhost ]# [ -e varlog/messages ]
  17. [root@localhost ]# echo $?
  18. 0
  19. [root@localhost ]# [ -e varlog/messages01 ]
  20. [root@localhost ]# echo $?
  21. 1

表14-1罗列了Shell中的所有文件比较符,它们的使用方法可参照之前的例子,只需参考表格中的“文件测试”部分改变相应的文件操作符即可。

表14-1 文件测试符

14.1.2 文件测试 - 图1

14.1.2 文件测试 - 图2

这里针对表14-1中最后两行内容——文件新旧的比较做一些说明。FILE1-nt FILE2中的-nt是newer than的意思,而FILE1-ot FILE2中的ot是older than的意思。文件新旧比较的主要使用场景是判断文件是否被更新或增量备份时,用于判断一段时间以来更新过的文件。

以下是参考表14-1写出的测试某个文件的读、写、执行属性的代码。


  1. [root@localhost ~]# cat rwx.sh
  2. #!/bin/bash
  3. read -p "What file do you want to test?" filename
  4. if [ ! -e "$filename" ]; then
  5. echo "The file does not exist."
  6. exit 1
  7. fi
  8. if [ -r "$filename" ]; then
  9. echo "$filename is readable."
  10. fi
  11. if [ -w "$filename" ]; then
  12. echo "$filename is writeable"
  13. fi
  14. if [ -x "$filename" ]; then
  15. echo "$filename is executable"
  16. fi