David Arutiunian
David Arutiunian

Reputation: 303

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

Upvotes: 0

Views: 2141

Answers (1)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70722

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"

Upvotes: 4

Related Questions