I am new in bash programming , was try to execute a program which will create a directory on basis of complete path provided to it from prompt and if directory already exists it will return error for directory already exists and ask again for name in recursive function. here it is what I did
let say a file test1 in it
#!/bin/bash
echo "enter the directory name"
read ab
check(){
if (( echo `mkdir $ab` 2>/dev/null )); then
echo "directory created "
echo `ls -ld $ab`
exit
else
echo "try again "
echo "enter new value for directory:
read ab
check
fi
}
check
the problem here is if the directory exists then the program works fine but if does not exist then it creates it but then goes to the else part of the program . please help
You can use a test to see if the directory exists. If you want to repeatedly ask for a directory name until you get one, use a loop:
while true
do
read -p"Directory Name: " directory
if [[ -d $directory ]] # Directory already exists
then
echo "Directory '$directory' already exists. Try again."
continue
fi
mkdir "$directory" && break
echo "Cannot create directory $directory"
exit 2 # Or whatever
done
A while true
loop is an infinite loop. However, I have two loop controls in the loop: A continue
statement that goes back to the top of the loop, and a break
statement that ends the loop. It's why that infinite loop (like all infinite loops) isn't really infinite.
I use [[ -d "$directory" ]]
to test to see if the directory already exists or not. If it already does exist, I'll echo something to that effect, and use continue
to go back and re-prompt for the directory name.
Note that my read
uses a -p
parameter. This is my prompt used for the read
command. It's a nice easy way to combine the read with the prompt.
mkdir "$directory" && break
means to make the directory. The &&
is a list operator. It says to run the command on the left (the mkdir
) and if it is successful (i.e. it returns a zero exit status), then run the command on the right (the break
) and exit my loop. It's equivalent to:
If mkdir "$directory"
then
break
fi
The other list operator is ||
. It says if the command on the left failed (that it returned a non-zero exit status), then run the command on the right.
For example:
[[ -d $directory ]] || mkdir "$directory"
is equivalent to:
if [[ ! -d $directory ]]
then
mkdir "$directory"
fi
I through in a lot of things in here on purpose to demonstrate a lot of standard things you'll see in various shell scripts.
[[ ... ]]
for testing. There are lots of various tests for files, directories, strings, and boolean tests. Learn them.-p
for read prompts.continue
and break
. It's not unusual to use loops like this to make sure the correct parameter is entered.