[ parameter FILE ]
OR
test parameter FILE
Where parameter can be any one of the following:
- -e: Returns true value if file exists
- -f: Return true value if file exists and regular file
- -r: Return true value if file exists and is readable
- -w: Return true value if file exists and is writable
- -x: Return true value if file exists and is executable
- -d: Return true value if exists and is a directory
Find out if file /etc/passwd file exists or not:
$ [ -f /etc/passwd ] && echo "File exists" || echo "File does not exists"
# Make the directory for the job ID you are running if it does not exist
[ -d $HOME/scratch/jobid_$JOB_ID ] || mkdir -p $HOME/scratch/jobid_$JOB_ID
You can use conditional expressions in a shell script: #!/bin/bashSee if a directory exists or not with NOT operator:
FILE=$1
if [ -f $FILE ];
then
echo "File $FILE exists"
else
echo "File $FILE does not exists"
fi
[ ! -d directory ]
OR
! test directory
In Perl, use "-d" to see if a directory exists, as
ReplyDeleteif (-d "../citydata") {
print "There is a directory named citydata!";
}
else {
print "There is a no such directory.";
}
"-e" for file existence:
if (-e "../cities.txt") {
print "File exists!";
}
else {
print "File does not exist.";
}