Monday, October 11, 2010

file/folder existence

General syntax in BASH shell is:

[ 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
For example,

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/bash
FILE=$1

if [ -f $FILE ];
then
echo "File $FILE exists"
else
echo "File $FILE does not exists"
fi
See if a directory exists or not with NOT operator:
[ ! -d directory ]
OR
! test directory

1 comment:

  1. In Perl, use "-d" to see if a directory exists, as

    if (-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.";
    }

    ReplyDelete