user3524591
user3524591

Reputation: 21

I need to test for a directory in unix

I am making a simple shell script, I need to test for a directory, if it is there, delete it and create a new one, if it is not there, create it.

this is what I have so far:

if ( ! -d /numbers ); then
        echo "does not exist, creating directory"
        sleep 3s
        mkdir numbers
        echo "Directory created."
else
        echo "Removing existing directory and creating a new one"
        sleep 2s
        rmdir numbers
        echo "directory removed"
        sleep 1s
        mkdir numbers
        echo "Directory created"
fi

but this gives me an error message:

myscript.sh: line 17: -d: command not found

and if the directory is there:

mkdir: cannot create directory `numbers': File exists

Upvotes: 1

Views: 67

Answers (1)

Jake
Jake

Reputation: 58

You need to use square brackets for the test in the if statement. You're also using rmdir, which will only work if the directory is empty. If you want to delete it and its content, use rm -r numbers.

Maybe something like this:

if [ ! -d numbers ]; then
        echo "does not exist, creating directory"
        sleep 3s
        mkdir numbers
        echo "Directory created."
else
        echo "Removing existing directory and creating a new one"
        sleep 2s
        rm -r numbers
        echo "directory removed"
        sleep 1s
        mkdir numbers
        echo "Directory created"
fi

Upvotes: 1

Related Questions