sudhir kumar sudhir kumar - 2 months ago 11
Bash Question

Shell script for directory creation

I wrote a shell script to create a directory if it doesn't exist. I am able to create a new directory. But when I pass an existing directory name the

elif
statement is not being executed, instead
Created Directory
is printing. What am doing wrong?

if [[ ! -e /test/{a,b,c}/$dirname ]]; then
mkdir "/test/{a,b,c}/$dirname"
echo "Created Directory"
elif [[ ! -d /test/{a,b,c}/$dirname ]]; then
echo "$dirname already exists"
fi


Here
test
,
a
,
b
, and
c
are directories.

Answer

Brace expansion isn't a globbing form performed on unquoted expansion. Consequently, you can't rely on for dir in $dirs: You need to either use an array to store brace expansion results, or iterate over such results directly.

If you want to create any directories only if none of the directories already exist:

# assign to an array
dirs=( /test/{a,b,c}/"$dirname" )

# iterate over contents and check, failing if any exists
for dir in "${dirs[@]}"; do
  [[ -d "$dir" ]] && { echo "$dir already exists" >&2; exit 1; }
done

# if we reach here, none of them exist, so create all directories with one mkdir call.
mkdir -- "${dirs[@]}" || exit # also, fail the script if mkdir fails

Alternately, if it's acceptable to take partial action:

for dir in /test/{a,b,c}/"$dirname"; do
  [[ -d "$dir" ]] && { echo "$dir already exists" >&2; exit 1; }
  mkdir -- "$dir"
done
Comments