My way on Linux - [Shell基础] - Bash Shell中判断文件、目录是否存在或者判断其是否具有某类属性(权限)的常用方法

时间:2021-09-22 05:21:02

Conditional Logic on Files

# 判断文件是否存在及文件类型

-a    file exists.    #文件存在
-b file exists and is a block special file. #文件存在,并且是块设备
-c file exists and is a character special file. ##文件存在,并且是字符设备
-d file exists and is a directory. #文件存在,并且是目录
-e file exists (just the same as -a). #文件存在
-f file exists and is a regular file. #文件存在,并且是普通文件
-L file exists and is a symbolic link. #文件存在,并且符号链接
-p file exists and is a first in, first out (FIFO) special file or named pipe. #文件存在,并且是管道设备或FIFO设备
-S file exists and is a socket. #文件存在,并且是套接字(socket)文件
-s file exists and has a size greater than zero. #文件存在,并且文件大小非零(大于零)

# 判断文件是否存在,并有相关权限的属性

# 常规属性
-r file exists and is readable by the current process. #文件存在,并且本进程可读
-w file exists and is writable by the current process. #文件存在,并且本进程可写
-x file exists and is executable by the current process. #文件存在,并且本进程可执行 # 扩展属性
-u file exists and has its setuid() bit set. #文件存在,并且有setuid属性
-g file exists and has its setgid() bit set. #文件存在,并且有setgid属性
-k file exists and has its sticky bit set. #文件存在,并且有粘滞位
-G file exists and has the same group ID as this process. #文件存在,并且与本进程拥有相同的GID
-O file exists and is owned by the user ID of this process. #文件存在,并且与本进程拥有相同的UID

# 字符长度判断

-z    string length is zero.    #字符串长度为零返回true
-n string length is not zero. #字符串长度非零返回true

# 其他选项(这个地方没太懂,还请各位赐教)

-t    file descriptor number fildes is open and associated with a terminal device.    #文件描述符??是打开的,并且同终端设备有关
-o Named option is set on. #开启了命名选项??

# 两个文件之间的比较

-nt    #newer than,判断 file1 是否比 file2 新,通过比较文件的时间戳实现
-ot #older than,判断 file1 是否比 file2 旧,通过比较文件的时间戳实现
-ef #equal file,判断 file2 与 file2 是否为同一档案,通过判断两个文件指向的的inode是否相同来实现,可用在hard link(硬链接) 的判定上

# 两个整数之间的比较

-eq    #equal  等于
-ne #not equal 不等于
-gt #greater than 大于
-lt #less than 小于
-ge #greater than or equal 大于等于
-le #less than or equal 小于等于

# 多重条件判断

-a    #and 逻辑与,两状况同时成立则返回true
-o #or 逻辑或,两状况任何一个成立则返回true
! #not 逻辑非,状态相反则返回true

常用判断的Shell样例

#!/bin/bash

myPath="/var/log/nginx/"
myFile="/var /log/nginx/access.log" # -x 参数 判断$myPath是否存在并且是否具有可执行权限
if [ ! -x "$myPath"]; then
mkdir "$myPath"
fi # -d 参数 判断$myPath是否存在,并且属性是个目录
if [ ! -d "$myPath"]; then
mkdir "$myPath"
fi # -f参数 判断$myFile是否存在,并且属性是个普通文件
if [ ! -f "$myFile" ]; then
touch "$myFile"
fi # -n参数 判断一个变量是否是否有值
if [ ! -n "$myVar" ]; then
echo "$myVar is empty"
exit 0
fi # 两个变量判断是否相等
if [ "$var1" = "$var2" ]; then
echo '$var1 eq $var2'
else
echo '$var1 not eq $var2'
fi