Unix / Linux - Shell 文件测试运算符示例
我们有一些运算符可用于测试与 Unix 文件关联的各种属性。
假设一个变量file 包含一个现有的文件名"test",其大小为100 字节并且具有read、write 和execute权限 −
运算符 | 说明 | 示例 |
---|---|---|
-b file | 检查文件是否是块特殊文件; 如果是,则条件成立。 | [ -b $file ] 为 false。 |
-c file | 检查文件是否为字符特殊文件; 如果是,则条件成立。 | [ -c $file ] 为 false。 |
-d file | 检查文件是否是一个目录; 如果是,则条件成立。 | [ -d $file ] 为 not true。 |
-f file | 检查文件是否是普通文件而不是目录或特殊文件; 如果是,则条件成立。 | [ -f $file ] 为 true。 |
-g file | 检查文件是否设置了组 ID (SGID) 位; 如果是,则条件成立。 | [ -g $file ] 为 false。 |
-k file | 检查文件是否设置了粘滞位; 如果是,则条件成立。 | [ -k $file ] 为 false。 |
-p file | 检查文件是否为命名管道; 如果是,则条件成立。 | [ -p $file ] 为 false。 |
-t file | 检查文件描述符是否打开并与终端关联; 如果是,则条件成立。 | [ -t $file ] 为 false。 |
-u file | 检查文件是否设置了其设置用户 ID (SUID) 位; 如果是,则条件成立。 | [ -u $file ] 为 false。 |
-r file | 检查文件是否可读; 如果是,则条件成立。 | [ -r $file ] 为 true。 |
-w file | 检查文件是否可写; 如果是,则条件成立。 | [ -w $file ] 为 true。 |
-x file | 检查文件是否可执行; 如果是,则条件成立。 | [ -x $file ] 为 true。 |
-s file | 检查文件大小是否大于 0; 如果是,则条件变为真。 | [ -s $file ] 为 true。 |
-e file | 检查文件是否存在; 即使文件是目录但存在也是如此。 | [ -e $file ] 为 true。 |
示例
下面的例子使用了所有的文件测试操作符 −
假设一个变量文件包含一个现有的文件名 "/var/www/tutorialspoint/unix/test.sh" 其大小为 100 字节并且具有read , write 和 execute 权限 −
#!/bin/sh file="/var/www/tutorialspoint/unix/test.sh" if [ -r $file ] then echo "File has read access" else echo "File does not have read access" fi if [ -w $file ] then echo "File has write permission" else echo "File does not have write permission" fi if [ -x $file ] then echo "File has execute permission" else echo "File does not have execute permission" fi if [ -f $file ] then echo "File is an ordinary file" else echo "This is sepcial file" fi if [ -d $file ] then echo "File is a directory" else echo "This is not a directory" fi if [ -s $file ] then echo "File size is not zero" else echo "File size is zero" fi if [ -e $file ] then echo "File exists" else echo "File does not exist" fi
上面的脚本会产生下面的结果 −
File does not have write permission File does not have execute permission This is sepcial file This is not a directory File size is not zero File does not exist
使用文件测试算子需要注意以下几点 −
运算符和表达式之间必须有空格。 例如,2+2 是不正确的; 应该写成 2 + 2。
if...then...else...fi 语句是决策语句,已在下一章中解释。