Shell Script - create a directory if it does not exist

I want to enter a directory name and check if it exists. If it does not exist, I want to create, but I get an errormkdir: cannot create directory'./' File exists

My code says that the file exists even if it does not. 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
+4
source share
4 answers
if [ -L $dirname]

, : "[: missing`]" ( ). . , ; : - "$foo", "$(foo)".

if [ -L "$dirname" ]

: , , . , .

, , script , , , , . "check then do" , " " .

, ,

mkdir -p -- "$dirname"

( $dirname , -- , -.)

+7

:

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

:

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
+1

: ls yourdir 2>/dev/null||mkdir yourdir, .

+1
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
0

Source: https://habr.com/ru/post/1535355/


All Articles