2

The user inputs the file path and the shell script must check for file existence and if the file doesn't exist, prompt for correct path until the correct path is provided. Here is my attempt and I don't like it

if [[ -z $filepath || ! -f $filepath  ]]; then
    printf "\nError: File does not exist. Try again\n"

    while true :
    do
        read -p "Please provide file path: " filepath
        if [[ -z $filepath || ! -f $filepath  ]]; then
            continue
        else 
            break
        fi 
    done
fi

and here is another try which failed due to syntax errors

if [[ -z $filepath || ! -f $filepath  ]]; then 
    printf "\nError: Bad file path. Try again\n" 
    while true : 
    do 
        read -p "Please enter file path: " filepath
        case $filepath in
                "")
                    echo "Bad file path. Try again"
                    continue ;;
                ! -f)
                    echo "Bad file path. Try again"
                    continue ;; 
                *)
                    break ;;
        esac
    done
Ali
  • 7,810
  • 12
  • 42
  • 65

2 Answers2

1

I think you just want a while loop while the file doesn't exist. You could do something like,

read -p "Please provide file path: " filepath
while [[ ! -f "$filepath" ]]; do
    printf "Bad file path ($filepath). Try again\n"
    read -p "Please provide file path: " filepath
done
printf "$filepath exists\n"
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Your solution is actually more easily understandable but the other one has less lines of code – Ali Nov 18 '15 at 00:26
  • 1
    @Ali Unless I'm missing something, they have the same number of lines if you omit the bad file path error message. – Elliott Frisch Nov 18 '15 at 04:09
1

How about

until [[ -n $filepath && -f $filepath ]]; do
    read -p "Please provide file path: " filepath
done
glenn jackman
  • 238,783
  • 38
  • 220
  • 352