0

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:

#!/bin/bash

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

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?

1 Answers1

0

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.