I have written a script to check in var/log directory, and it takes all the directories in there and checks if there is an archive directory in those directories. If an archive directory not exist, I want to create it, but once it's created the script tries to create it again.
vdir=$(sudo sh -c "find /var/log/ -maxdepth 1 -type d ! -name "archive"" )
for i in $vdir ;do
echo $i
if [[ ! -d $i/$arc ]];then
sudo sh -c "mkdir $i/$arc"
echo "$date:$HN:Creating:$i/$arc:directory" >> logrotation.log
fi
done
When I execute above code it gives me this error. Seems the script is not checking the condition.
mkdir: cannot create directory ‘/var/log/speech-dispatcher/archive’: File exists
Checking If a Directory Exists In a Bash Shell Script-h "/path/to/dir" ] && echo "Directory /path/to/dir exists." || echo "Error: Directory /path/to/dir exists but point to $(readlink -f /path/to/dir)." The cmd2 is executed if, and only if, cmd1 returns a non-zero exit status.
You can use test -d (see man test ). -d file True if file exists and is a directory. Note: The test command is same as conditional expression [ (see: man [ ), so it's portable across shell scripts.
A test in bash is not a test that your program works. It's a way of writing an expression that can be true or false. Tests in bash are constructs that allow you to implement conditional expressions. They use square brackets (ie [ and ] ) to enclose what is being tested.
The issue is that you have two [
symbols. You only need one:
if [ ! -d $i/$arc ];then
An additional point: some shell versions don't handle the ;
being right next to the closing bracket. Thus, I'd suggest formatting like this for best compatibility:
if [ ! -d $i/$arc ] ; then
Edit: since the above didn't help you, more thoughts:
It's also entirely possible that your script, running as you, can't actually read the contents of the $i
directory and thus the test will always fail (or succeed, actually). But, when you create the directory as root via sudo, it already exists.
[It would also be more efficient to run the entire script under sudo rather than just certain pieces of it.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With