Shell Script - Make directory if it doesn't exist Shell Script - Make directory if it doesn't exist shell shell

Shell Script - Make directory if it doesn't exist


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


Try this code:

echo "Enter directory name"read dirnameif [ ! -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$ lsdir.shChitta:~/cpp/shell$ sh dir.shEnter directory nameNew1File doesn't exist. Creating nowFile createdchitta:~/cpp/shell$ lsNew1  dir.shChitta:~/cpp/shell$ sh dir.shEnter directory nameNew1File existsChitta:~/cpp/shell$ sh dir.shEnter directory nameNew2File doesn't exist. Creating nowFile createdChitta:~/cpp/shell$ lsNew1  New2  dir.sh


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