Checking whether a file exists

Files / Basic operations

fileName="file.txt"

#the file to look for
touch "$fileName"

#-e is true for anything with this name: a file or a directory
[[ -e "$fileName" ]] && exists1=true || exists1=false
#exists1 is true

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

#-f asks for a plain file, -d for a directory
[[ -f "." ]] && isFile=true || isFile=false
#isFile is false
[[ -d "." ]] && isDir=true || isDir=false
#isDir is true

#-s is true only for a file that is not empty
[[ -s "$fileName" ]] && notEmpty=true || notEmpty=false
#notEmpty is false: touch made an empty file

#the second method: stat fails for a name that is not there
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"