I'm trying to prompt user repeatedly enter a directory and then the script will then check if the directory exists, if not keep prompting till the user enter a valid directory.

my code:


while :
echo "Enter a directory:"
read directory
if [ -f $directory ]
cd $directory
echo "Directory does not exists, please try again."

The problem now is even when I enter the valid directory e.g /home/username it's still looping instead of changing that directory, any idea what went wrong?

  • 2
    -f is a test for regular files; it's -d for directories Commented Feb 11, 2020 at 13:20
  • Ok I amended my code with -d now the loop stops but it still won't change to the valid directory when I enter e.g /home I use the pwd command to see the directory does not change Commented Feb 11, 2020 at 13:30
  • 1
    This is expected, you're changing directory in a sub shell then returning to your current shell. See - unix.stackexchange.com/questions/27139/… Commented Feb 11, 2020 at 13:32
  • How are you determining that it doesn't change to the directory? Are you aware of why cd works in shell but not in script Commented Feb 11, 2020 at 13:34

1 Answer 1


I ran the code as you've typed, it worked well, I change the -f to -d though, since you wanted to check for a directory. You have to use the source built-in command to run the shell script

$ source script_name.sh

The cd command runs in a sub-shell environment, so when the command is executed the directory is changed if the $directory is valid according to the test conducted by if statement.

When the sub-shell environment returns control back to the parent shell, the change in the environment(cd $directory) is not passed on to the parent shell. So, you just remain in the same directory.

Source will run the script in the current shell itself, so if the cd command is executed successfully, the change is visible.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .