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?

  • 2
    -f is a test for regular files; it's -d for directories – steeldriver Feb 11 '20 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 – user3815380 Feb 11 '20 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/… – rusty shackleford Feb 11 '20 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 – steeldriver Feb 11 '20 at 13:34
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.