Wednesday, 1 May 2013

HowTo: Check If a Directory Exists In a Shell Script

How do I check if a directory exists in a shell script under Linux or Unix like operating systems?

To check if a directory exists and is a directory use the following syntax:
[ -d "/path/to/dir" ] && echo "Directory /path/to/dir exits." || echo "Error: Directory /path/to/dir does not exits."

The following version also check for symbolic link:
[ -d "/path/to/dir" && ! -L "/path/to/dir" ] && echo "Directory /path/to/dir exits." || echo "Error: Directory /path/to/dir exits but point to $(readlink -f /path/to/dir)."
OR
[ -d "/path/to/dir" && ! -h "/path/to/dir" ] && echo "Directory /path/to/dir exits." || echo "Error: Directory /path/to/dir exits but point to $(readlink -f /path/to/dir)."
Finally, you can use the traditional if..else..fi:
if [ -d "/path/to/dir" ]
then
    echo "Directory /path/to/dir exits."
else
    echo "Error: Directory /path/to/dir does not exits."
fi

Shell script examples to see if a ${directory} exists or not

 
#!/bin/bash
dir="$1"
 
[ $# -eq 0 ] && { echo "Usage: $0 dir-name"; exit 1; }
 
if [ -d "$dir" -a ! -h "$dir" ]
then
   echo "$dir found and setting up new Apache/Lighttpd/Nginx jail, please wait..."
   # __WWWJailSetup "cyberciti.biz" "setup"
else
   echo "Error: $dir not found or is symlink to $(readlink -f ${dir})."
fi
In this example, create directories if does not exits:
# Purpose: Setup jail and copy files
# Category : Core
# Override : No
# Parameter(s) : d => domain name
#                action => setup or update
__WWWJailSetup(){
        local d="$1"
        local action="${2:setup}"       # setup or update???
        local index="<html><head><title>$d</title></head><body><h1>$d</h1></body></html>" # default index.html
        local J="$(_getJailRoot $d)/$d" # our sweet home 
        local _i=""
 
        [ "$action" == "setup" ] && echo "* Init jail config at $J..." || echo "* Updating jail init config at $J..."
        __init_domain_config "$d"
 
        [ "$action" == "setup" ] && echo "* Setting up jail at $J..." || echo "* Updating jail at $J..."
        [ ! -d "$J" ] &&  $_mkdir -p "$J"
 
        for _i in $J/{etc,tmp,usr,var,home,dev,bin,lib64}
        do
                [ ! -d "$_i" ] &&  $_mkdir -p "$_i"
        done
        for _i in $_lighttpd_webalizer_base/$d/stats/{dump,out}
        do
                [ ! -d "$_i" ] &&  $_mkdir -p "$_i"
        done
        for _i in $_lighttpd_webalizer_prepost_base/$d/{pre.d,post.d}
        do
                [ ! -d "$_i" ] &&  $_mkdir -p "$_i"
        done
## truncated 
}

No comments:

Post a Comment