【问题标题】:Shell script read file path until file exisitsShell脚本读取文件路径,直到文件存在
【发布时间】:2016-02-19 13:30:33
【问题描述】:

用户输入文件路径,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

【问题讨论】:

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


    【解决方案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"
    

    【讨论】:

    • 您的解决方案实际上更容易理解,但另一个解决方案的代码行数更少
    • @Ali 除非我遗漏了什么,否则如果您省略错误的文件路径错误消息,它们的行数相同。
    【解决方案2】:

    怎么样

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 1970-01-01
      • 2017-03-12
      • 2016-07-25
      • 2014-02-24
      相关资源
      最近更新 更多