While Loop Not Working Properly
Coming from a Python Background, I'm Now Learning Bash Scripting. I Am Having a Bit of Trouble with a While Loop. While Trying to Create a Simple Script That...
Coming from a Python background, I'm now learning Bash scripting. I am having a bit of trouble with a while loop. While trying to create a simple script that creates a new directory, the output behaves erratically.
In my first attempt using the script below:
#!/bin/bash
while :
do
echo 'Enter directory name:'
read newdir
`mkdir $newdir`
echo "[+] Directory created!"
break
if [ -d $newdir ];then
echo "[-] cannot create directory. $newdir already exists."
fi
done
The output is correct:
xuser@xuser-VB:~/Scripts$ ./newdir.sh
Enter directory name:
abc
[+] Directory created!
However, if I try to create a directory with the same name, it still outputs the [+] Directory created! on top of the system error message.
xuser@xuser-VB:~/Scripts$ ./newdir.sh
Enter directory name:
abc
mkdir: cannot create directory ‘abc’: File exists
[+] Directory created!
what am I missing or forgetting?
1 Answer
You need to check the existence of the directory before creating it.
#!/bin/bash
while :
do
echo 'Enter directory name:'
read newdir
if [ -d "$newdir" ] ; then
echo "[-] cannot create directory. $newdir already exists."
continue
fi
mkdir -- "$newdir"
echo "[+] Directory created!"
break
done
I also removed the backquotes, mkdir doesn't output anything, so they aren't useful in this context.
Moreover, double quote variables - without double quotes, directory names containing spaces would not work.
Using mkdir -- "$newdir" will interpret the $newdir as the directory name even if it starts with a dash.