Question

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
Was it helpful?

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

OTHER TIPS

Try this code:

echo "Enter directory name"
read dirname

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

Output Log:

Chitta:~/cpp/shell$ ls
dir.sh

Chitta:~/cpp/shell$ sh dir.sh
Enter directory name
New1
File doesn't exist. Creating now
File created

chitta:~/cpp/shell$ ls
New1  dir.sh

Chitta:~/cpp/shell$ sh dir.sh
Enter directory name
New1
File exists

Chitta:~/cpp/shell$ sh dir.sh
Enter directory name
New2
File doesn't exist. Creating now
File created

Chitta:~/cpp/shell$ ls
New1  New2  dir.sh

try this: ls yourdir 2>/dev/null||mkdir yourdir, which is tiny and concise and fulfils your task.

read -p "Enter Directory Name: " dirname
if [[ ! -d "$dirname" ]]
then
        if [[ ! -L $dirname ]]
        then
                echo "Directory doesn't exist. Creating now"
                mkdir $dirname
                echo "Directory created"
        else
                echo "Directory exists"
        fi
fi
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top