文件属性比较
时间:2019-04-16 23:59:04 来源:igfitidea点击:
在shell中,使用test
命令和[]
条件表达式可以测试各种文件属性。
shell判断文件是否存在 -a file
如果文件存在,则为true
示例
[ -a /etc/resolv.conf ] && echo "File found" || echo "Not found"
shell判断文件是否存在并且是否为块设备文件 -b file
如果文件存在并且是块设备文件,则为true
示例
[ -b /dev/zero ] && echo "block special file found" || echo "block special file not found" [ -b /dev/sdb ] && echo "block special file found" || echo "block special file not found"
shell判断文件是否存在并且是否为字符设备文件 -c file
如果文件存在且为字符设备文件,则为true
示例
[ -c /dev/tty0 ] && echo "Character special file found." || echo "Character special file not found."
shell如何判断目录是否存在 -d dir
如果dir是目录并且存在,则为true
示例
#!/bin/bash DEST="/backup" # 如果目录不存在,则创建 [ ! -d "$DEST" ] && mkdir -p "$DEST"
shell判断文件是否存在 -e file
如果文件存在,则为true
示例
[ -e /tmp/test.txt ] && echo "File found" || echo "File not found"
shell判断文件是否为普通文件 -f file
如果文件存在并且是普通文件,则为true
示例
[ ! -f /path/to/file ] && echo "File not found!"
shell判断文件是否为链接 -h file
如果文件是链接文件,则为true
示例
[ -r /etc/resolv.conf ] && echo "File is a symbolic link" || echo " The file is not a symbolic link"
shell判断文件是否为命名管道 -p file
如果是命名管道,则为true
示例
[ -r /etc/resolv.conf ] && echo "File is a named pipe" || echo " The file is not a named pipe"
shell判断文件是否可读 -r file
如果文件可读,则为true
示例
[ -r /etc/resolv.conf ] && echo "File is readable" || echo "is Not readable"
shell判断文件是否可写 -w file
如果文件可写,则为true
示例
[ -w /etc/resolv.conf ] && echo "File is writable" || echo "is Not writable"
shell判断文件是否可执行 -x file
如果文件有可执行权限,则为true
示例
[ -x /etc/resolv.conf ] && echo "File is executable" || echo "is Not executable"
shell判断文件大小是否大于0 -s file
如果文件大小大于0,则为true
示例
[ -s /path/to/file ] && echo "File size >0 !"
shell判断文件是否为socket -S file
如果文件是socket,则为true
示例
[ -r /etc/resolv.conf ] && echo "File is a socket" || echo " The file is not a socket "