Wednesday, October 27, 2021

[SOLVED] Shell Script - Make directory if it doesn't exist

Issue

I want to enter the name of a directory and check if it exists. If it doesn't exist I want to create but I get the error mkdir: cannot create directory'./' File exists

My code says that the file exists even though it doesn't. What am I doing wrong?

echo "Enter directory name"
read dirname

if [[ ! -d "$dirname" ]]
then
    if [ -L $dirname]
then
    echo "File doesn't exist. Creating now"
    mkdir ./$dirname
    echo "File created"
    else
        echo "File exists"
    fi
fi

Solution

if [ -L $dirname]

Look at the error message produced by this line: “[: missing `]'” or some such (depending on which shell you're using). You need a space inside the brackets. You also need double quotes around the variable expansion unless you use double brackets; you can either learn the rules, or use a simple rule: always use double quotes around variable substitution and command substitution"$foo", "$(foo)".

if [ -L "$dirname" ]

Then there's a logic error: you're creating the directory only if there is a symbolic link which does not point to a directory. You presumably meant to have a negation in there.

Don't forget that the directory might be created while your script is running, so it's possible that your check will show that the directory doesn't exist but the directory will exist when you try to create it. Never do “check then do”, always do “do and catch failure”.

The right way to create a directory if it doesn't exist is

mkdir -p -- "$dirname"

(The double quotes in case $dirname contains whitespace or globbing characters, the -- in case it starts with -.)



Answered By - Gilles 'SO- stop being evil'