检查文件是否存在

文件操作 / 基本操作

fileName="file.txt"

#要查找的文件
touch "$fileName"

#-e 对任何同名的对象都为真:文件或目录
[[ -e "$fileName" ]] && exists1=true || exists1=false
#exists1 is true

[[ -e "absent.txt" ]] && exists2=true || exists2=false
#exists2 is false

#-f 检查是否为普通文件,-d 检查是否为目录
[[ -f "." ]] && isFile=true || isFile=false
#isFile is false
[[ -d "." ]] && isDir=true || isDir=false
#isDir is true

#-s 只对非空文件为真
[[ -s "$fileName" ]] && notEmpty=true || notEmpty=false
#notEmpty 为 false,因为 touch 创建的是空文件

#第二种方法:对不存在的名称,stat 会失败
stat "absent.txt" > /dev/null 2>&1 && exists3=true || exists3=false
#exists3 is false

echo "exists1 is $exists1"
echo "exists2 is $exists2"
echo "isFile is $isFile"
echo "isDir is $isDir"
echo "notEmpty is $notEmpty"
echo "exists3 is $exists3"
rm "$fileName"