What command can be used to check if a directory exists or not, within a Bash shell script?
if [ -d "$Directory" -a -w "$Directory" ]
then
#Statements
fi
The above code checks if the directory exists and if it is writable.
file="foo"
if [[ -e "$file" ]]; then echo "File Exists"; fi;
I find the double-bracket version of test
makes writing logic tests more natural:
if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
echo "It's a bona-fide directory"
fi
[[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"
N.B: Quoting variables is a good practice.
Explanation:
-d
: check if it's a directory-L
: check if it's a symbolic linkTo check if a directory exists you can use a simple if
structure like this:
if [ -d directory/path to a directory ] ; then
# Things to do
else #if needed #also: elif [new condition]
# Things to do
fi
You can also do it in the negative:
if [ ! -d directory/path to a directory ] ; then
# Things to do when not an existing directory
Note: Be careful. Leave empty spaces on either side of both opening and closing braces.
With the same syntax you can use:
-e: any kind of archive
-f: file
-h: symbolic link
-r: readable file
-w: writable file
-x: executable file
-s: file size greater than zero
Use the file
program.
Considering all directories are also files in Linux, issuing the following command would suffice:
file $directory_name
Checking a nonexistent file: file blah
Output: cannot open 'blah' (No such file or directory)
Checking an existing directory: file bluh
Output: bluh: directory