23

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
BSMP
  • 4,596
  • 8
  • 33
  • 44
SLS
  • 445
  • 1
  • 6
  • 20

1 Answers1

27

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.]

Wes Hardaker
  • 21,735
  • 2
  • 38
  • 69
  • Thanks for the help, I have made this changes, Nothing happen. Still trying to create directory when is is there, But for some directory it work. Not sure the reason of it. – SLS Jan 26 '17 at 07:52
  • 1
    Huh? `[[` is the Bash souped-up replacement for traditional `[`. It works just fine as long (as your shell is in fact Bash!) and certainly does not produce the error message described by the OP. – tripleee Jan 26 '17 at 08:04