The meaning of each parameter judged by the file in the shell

1. Judgment content corresponding to each option

-e filename 如果 filename存在,则为真
-d filename 如果 filename为目录,则为真
-f filename 如果 filename为常规文件,则为真
-L filename 如果 filename为符号链接,则为真
-r filename 如果 filename可读,则为真
-w filename 如果 filename可写,则为真
-x filename 如果 filename可执行,则为真
-s filename 如果文件长度不为0,则为真
-h filename 如果文件是软链接,则为真

2. Commonly used examples

1. Determine whether the folder exists

#shell判断文件夹是否存在,如果文件夹不存在,创建文件夹
#!/bin/bash
if [ ! -d "/data/test" ]; then
   mkdir /data/test
fi

2. Determine whether the file has executable permissions

#shell判断文件,目录是否存在或者具有权限
#!/bin/bash

folder="/data/test/"
file="/data/test/log"

# -x 参数判断 $file 是否具有可执行权限
if [ ! -x "$file" ]; then
   chmod +x $file
fi

3. Determine whether the folder exists

# -d 参数判断 $folder 是否存在
if [ ! -d "$folder" ]; then
   mkdir "$folder"
fi

4. Determine whether the file exists

# -f 参数判断 $file 是否存在
if [ ! -f "$file" ]; then
   touch "$file"
fi

5. Determine whether a variable has a value

# -n 判断一个变量是否有值
if [ ! -n "$var" ]; then
   echo "$var is empty"
   exit 0
fi

6. Determine whether two variables are equal

# 判断两个变量是否相等

if [ "$var1" = "$var2" ]; then
   echo '$var1 eq $var2'
else
   echo '$var1 not eq $var2'
fi

 

Guess you like

Origin blog.csdn.net/l_liangkk/article/details/114994632