Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if directory does not exist [duplicate]

Tags:

linux

bash

shell

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
like image 281
SLS Avatar asked Jan 26 '17 07:01

SLS


People also ask

How do you check if directory does not exist in Bash?

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.

How to check in shell script if a directory exists?

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.

What is Bash test?

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.


1 Answers

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

like image 172
Wes Hardaker Avatar answered Sep 17 '22 17:09

Wes Hardaker