loop for file location until file exists in bash

为君一笑 提交于 2019-12-02 00:01:58

Write the error to stderr

echo "File does not exist, please try again" >&2

You are saving all output from the function into the variable tempLoc, so even if the user inputs a valid file it will have a load of junk in the variable with it.

Stderr is where error messages should go anyway though, so it's good practice to send them there even without this problem.

Several things here:

You don't need () with "function" (and visa versa). () is usually preferred, (except in Korn shell).

ALWAYS write error messages to stderr: >&2, that is the main reason why it does not work. There are TWO instances where this is required.

Nothing to do with your issue, but it is a good idea to quote variable values, especially filenames: "$file". This is in case someone has whitespace in the filename. Not that anyone in their right mind would ever name a file or directory with an embedded space (Program Files). Using [[ ]] rather than single brackets reduces the need, but does not remove it altogether.

Always declare variables inside functions as local, unless you really need to use a global (which you usually don't). If you don't do that then the variables inside a function could stomp on those outside, particularly if you reuse the function in several scripts.

The if statement after calling the function is incorrect. You are testing for true/false (which it won't be) and you have omitted a $ prefix.

promptFile()
{
    local file

    while true
    do
        read -p "Please provide a full path [q to quit]: " file
        if [ "$file" == q ]; then
            echo "Exiting.." >&2
            return 1
        fi

        if [ ! -f "$file" ]; then
            echo "File does not exist, please try again" >&2
        else
            echo "$file"
            break
        fi
    done
}

tempLoc=$(promptFile)
if [ -n "$tempLoc" ]; then
   fileLocation=$tempLoc
fi 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!