Search code examples
shellloopsuser-inputfile-existscase-statement

Shell script read file path until file exisits


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

Solution

  • How about

    until [[ -n $filepath && -f $filepath ]]; do
        read -p "Please provide file path: " filepath
    done