1

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
shellter
  • 36,525
  • 7
  • 83
  • 90

1 Answers1

1

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
Jake
  • 58
  • 5
  • this does not work, it never makes it to the else statement, if the direcrtory is there it still runs the if statement for some reason – user3524591 Apr 20 '14 at 02:23
  • The directory it's checking to see if it exists is `/numbers`. Is the numbers directory in the root of the filesystem or is it in the same directory this script is being run from? – Jake Apr 20 '14 at 02:27
  • same directory its being run from, i changed it to "$numbers" instead of the /numbers – user3524591 Apr 20 '14 at 02:34
  • Try running the script in my updated answer. I just removed the / in the if statement. – Jake Apr 20 '14 at 02:36