Search code examples
linuxbashif-statementgnu

Test if directory exists or not


Here is my code, and it works but it always says that directory exist, doesnt matter what I write. Moreover it does not print a variable in echo $DIRECTORY. What I need to fix?

#!/bin/sh

if [ -d $DIRECTORY ]; then
echo "Directory exists"
elif [ ! -d $DIRECTORY ]; then
echo "Directory does not exists"
fi
echo $DIRECTORY

Solution

  • Passing variables to shell script

    • You have to instruct you script that DIRECTORY is a variable, passed as first script argument.
    • You have to enclose your variable into double-quotes in order to ensure spaces and special characters, like empty variables, to be correctly parsed.

    Sample:

    #!/bin/sh
    
    DIRECTORY="$1"
    
    if [ -d "$DIRECTORY" ]; then
        echo "Directory '$DIRECTORY' exists"
    else
        echo "Directory '$DIRECTORY' does not exists"
    fi
    echo "$DIRECTORY"
    

    Other sample:

    #!/bin/bash
    
    DIRECTORY="$1"
    FILE="$2"
    if [ -d "$DIRECTORY" ]; then
        if [ -e "$DIRECTORY/$FILE" ]; then
            printf 'File "%s" found in "%s":\n  ' "$FILE" "$DIRECTORY"
            /bin/ls -ld "$DIRECTORY/$FILE"
        else
            echo "Directory '$DIRECTORY' exists, but no '$FILE'!"
        fi
    else
        echo "Directory '$DIRECTORY' does not exists!"
    fi
    echo "$DIRECTORY/$FILE"