Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a while loop where I'm using -d option in test condition?

How do I test a directory in a while loop where if the directory doesn’t exist then it does the following blank things. I’m trying to prompt the user for input when the directory doesn’t exist so the user can retry. Once, they get it right then the script exits. My script has an infinite loop and I don’t know how to fix it. Here is what my bash script looks like:

#!/bin/bash

source_dir=$1
dest_dir=$2

while [[ ! -d "$source_dir" ]]
do
        echo "This is not a directory. Enter the source directory: "
        read "$source_dir"
done

while [[ ! -d "$dest_dir" ]]
do
        echo "This is not a directory. enter the destination directory: "
        read "$dest_dir"
done

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Certainly,

read "$source_dir"

does not make sense. To understand this, assume that your script is called with the parameter FOO. Hence, you first set source_dir to FOO, and the test [[ -d $source_dir ]] will do a [[ -d FOO ]] and the directory FOO does not exist. Therefore you perform your read command, which will parameter-expand into read FOO. This means to read one line from STDIN and store it into the variable FOO.

If you want to change the value of the variable source_dir, you have to do a

read source_dir
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading