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

Time:12-15

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

CodePudding user response:

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
  • Related