- Unix/Linux 初学者指南
- Unix/Linux - 首页
- Unix/Linux - 什么是Linux?
- Unix/Linux - 入门
- Unix/Linux - 文件管理
- Unix/Linux - 目录
- Unix/Linux - 文件权限
- Unix/Linux - 环境
- Unix/Linux - 基本工具
- Unix/Linux - 管道与过滤器
- Unix/Linux - 进程
- Unix/Linux - 通信
- Unix/Linux - vi 编辑器
- Unix/Linux Shell编程
- Unix/Linux - Shell 脚本
- Unix/Linux - 什么是Shell?
- Unix/Linux - 使用变量
- Unix/Linux - 特殊变量
- Unix/Linux - 使用数组
- Unix/Linux - 基本操作符
- Unix/Linux - 决策制定
- Unix/Linux - Shell 循环
- Unix/Linux - 循环控制
- Unix/Linux - Shell 替换
- Unix/Linux - 引号机制
- Unix/Linux - I/O 重定向
- Unix/Linux - Shell 函数
- Unix/Linux - 手册页帮助
- 高级 Unix/Linux
- Unix/Linux - 标准 I/O 流
- Unix/Linux - 文件链接
- Unix/Linux - 正则表达式
- Unix/Linux - 文件系统基础
- Unix/Linux - 用户管理
- Unix/Linux - 系统性能
- Unix/Linux - 系统日志
- Unix/Linux - 信号和陷阱
Unix/Linux - Shell 文件测试操作符示例
我们有一些操作符可以用来测试与Unix文件相关的各种属性。
假设变量file包含一个现有文件名"test",大小为100字节,并且具有读、写和执行权限:
| 操作符 | 描述 | 示例 |
|---|---|---|
| -b file | 检查文件是否为块特殊文件;如果是,则条件为真。 | [ -b $file ] 为假。 |
| -c file | 检查文件是否为字符特殊文件;如果是,则条件为真。 | [ -c $file ] 为假。 |
| -d file | 检查文件是否为目录;如果是,则条件为真。 | [ -d $file ] 为假。 |
| -f file | 检查文件是否为普通文件(相对于目录或特殊文件);如果是,则条件为真。 | [ -f $file ] 为真。 |
| -g file | 检查文件是否设置了其设置组ID (SGID) 位;如果是,则条件为真。 | [ -g $file ] 为假。 |
| -k file | 检查文件是否设置了其粘滞位;如果是,则条件为真。 | [ -k $file ] 为假。 |
| -p file | 检查文件是否为命名管道;如果是,则条件为真。 | [ -p $file ] 为假。 |
| -t file | 检查文件描述符是否已打开并与终端关联;如果是,则条件为真。 | [ -t $file ] 为假。 |
| -u file | 检查文件是否设置了其设置用户ID (SUID) 位;如果是,则条件为真。 | [ -u $file ] 为假。 |
| -r file | 检查文件是否可读;如果是,则条件为真。 | [ -r $file ] 为真。 |
| -w file | 检查文件是否可写;如果是,则条件为真。 | [ -w $file ] 为真。 |
| -x file | 检查文件是否可执行;如果是,则条件为真。 | [ -x $file ] 为真。 |
| -s file | 检查文件大小是否大于 0;如果是,则条件为真。 | [ -s $file ] 为真。 |
| -e file | 检查文件是否存在;即使文件是目录但存在,也为真。 | [ -e $file ] 为真。 |
示例
以下示例使用了所有文件测试操作符:
假设变量 file 包含现有文件名"/var/www/tutorialspoint/unix/test.sh",大小为 100 字节,并且具有读、写和执行权限:
#!/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 语句是决策语句,将在下一章中解释。
unix-basic-operators.htm
广告