Function getting called recursively

I have the below script which creates a directory or simply terminates without throwing error (exit 1) incase the directory exists.

bash-4.1$ vi mdir.sh
#!/bin/bash -e
shopt -s expand_aliases
alias mkdir=mkdir_s
mkdir_s(){
if [[ -d $1 ]]; then
echo " directory EXISTS "
return
else
echo " Creating DIRECTORY"
mkdir "$1"
return
fi
}

mkdir /tmp/mohta

It works fine when /tmp/mohta exists but runs in a recursive loop if the directory does not exists.

I understand why it is happening but not sure how to fix this.

Run mkdir with an absolute path.

Of course, if you just want a version of mkdir which doesn't return error when the folder already exists, standard POSIX-compliant mkdir can do that already: mkdir -p

1 Like

changing mkdir "$1" to /usr/bin/mkdir "$1" resolves the recursive problem !! Thank you ....

Another working solution might be to change

mkdir "$1"

to

env mkdir "$1"
1 Like