Shell脚本读取文件路径,直到文件存在

时间:2015-11-18 00:03:52

标签: shell loops user-input file-exists case-statement

用户输入文件路径,shell脚本必须检查文件是否存在,如果文件不存在,则提示正确的路径,直到提供正确的路径。这是我的尝试,我不喜欢它

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

这是另一个因语法错误而失败的尝试

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

2 个答案:

答案 0 :(得分:1)

我认为你只需要一个while循环而文件不存在。你可以做点什么,

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"

答案 1 :(得分:1)

怎么样

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