Chirality
Chirality

Reputation: 745

Reading a Directory and Verifying if it exists Bash

I have checked everywhere and tried many different "Solutions" on checking to see if the directory exists. Here's my code:

#!/bin/bash
echo -e "Where is the directory/file located?"
read $DIRECTORY
if [ -d "$DIRECTORY" ]; then
    echo "Exists!"
else
    echo "Does not exist!"
fi

What I am trying to do is have the user input a directory and for the script to check if it exists or not and return a result. This will ultimately tar/untar a directory. Regardless of whether the directory exists or not, it returns the answer "Does not exist!". (The input i'm trying is ~/Desktop, and from what I know that is 100% correct. Any concise answers are much appreciated :).

Upvotes: 0

Views: 68

Answers (1)

anubhava
anubhava

Reputation: 785146

Your script can be refactored to this:

#!/bin/bash

read -p 'Where is the directory/file located?' dir
[[ -d "$dir" ]] && echo 'Exists!' || echo 'Does not exist!'
  • Basically use read var instead of read $var
  • Better not to use all caps variable names in BASH/shell
  • Use single quotes while using ! in BASH since it denotes a history event

Upvotes: 2

Related Questions