Search code examples
shell

Testing to see if folder exists is not working as expected in shell script


I am trying to check if a directory exists or not in a user specified input. I have tried using the test -d <path_to_dir> and then subsequently checking the success of the command with $? -eq 1. But this does not seem to work as expected.

The problem is that for the first time I input a valid path, I get the incorrect path output. If I re-enter the same valid path the second time, it goes through.

Why is this happening? What am I missing? If this is not a good practive, how can I achieve this using something similar?

Here is my code:

read -p "Specify the path under which folder(s) need to be created: " var_dir_path
test -d var_dir_path
while [[ $? -eq 1 ]]; do
    read -p "Path specified is incorrect or directory does not exist. Try again: " var_dir_path
    test -d $var_dir_path
done

I tried debugging by adding an echo $? right after the first test command like below

read -p "Specify the path under which folder(s) need to be created: " var_dir_path
test -d var_dir_path
echo $?
while [[ $? -eq 1 ]]; do
    read -p "Path specified is incorrect or directory does not exist. Try again: " var_dir_path
    test -d $var_dir_path
done

and to my surprise, echo $? is returning 1 even though the path is a valid directory that exists. I'm not sure why this is happening.


Solution

  • You are missing the $ in the variable reference in your first test. This is testing for the existence of a directory named "var_dir_path":

    test -d var_dir_path
    

    Here's a corrected version:

    read -p "Specify the path under which folder(s) need to be created: " -r var_dir_path
    test -d "$var_dir_path"
    while [[ $? -eq 1 ]]; do
        read -p "Path specified is incorrect or directory does not exist. Try again: " -r var_dir_path
        test -d "$var_dir_path"
    done
    

    Edit

    Based on feedback from David C. Rankin in the comments, I revised the code in two other ways:

    1. Added quotes around the variable references in your test lines. This is mandatory in case the path given to you contains any spaces or other problematic characters.

    2. Added the -r flag to your read lines. This will ensure if the dir given to you contains any escaped characters, and you further use the $var_dir_path in commands later, the escaping will be preserved.