1

I am writing a simple script to check if an entered directory path exists. This is what I have

echo "Please specify complete directory path"
read file_path

for file in $file_path; do
    if [[ -d "$file" ]]; then
        echo "$file is a directory"
        break
    else
        echo "$file is not a directory, please try again."
fi
done

What I need is if it is not a directory to go back and ask for the file path again.

Thanks.

2 Answers 2

1

How about this?

echo "Please specify complete directory path"

while read file; do
    if [[ -d "$file" ]]; then
        echo "$file is a directory"
        break
    fi
    echo "$file is not a directory, please try again."
done
Sign up to request clarification or add additional context in comments.

2 Comments

Why not while read file instead of an infinite loop? You do need to handle the EOF case somehow, but that's missing in the code anyway.
Thanks for the speedy reply!
0

No need to split the path into its parts, testing the entire path with -d will tell you whether or not it is a directory. You need to put the entire test into a while loop until the user gets it right:

#/bin/sh
set -e
file_path=''
while [ ! -d "$file_path" ]
do
    echo "Please specify complete directory path"
    read file_path   
    if [ ! -d "$file_path" ]
    then
        echo "$file_path is not a directory, please try again."
    fi
done

I can use it like this

$ sh /tmp/test.sh 
Please specify complete directory path
foobar
foobar is not a directory, please try again.
Please specify complete directory path
/var/www

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.