loop for file location until file exists in bash

i have created this function:

function promptFile()

{

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

            if [ ! -f $file ]; then
                    echo "File does not exist, please try again"

            else
                    echo $file
                    break
            fi
    done
}

To prompt a user for file location, ask again if file does not exist, and save the output to a variable if it does, the function is called:

tempLoc=$(promptFile)
if [ !tempLoc ]; then
        fileLocation=$tempLoc
fi

Everything works well unless someone write a bad file location, then the echo is not shown until someone clicks q or inputs an existing file location.
in which case the echo message will be printed * the number of bad inputs, as follows.

[root@tsting:0]# ./tst
Please provide a full path [q to quit]: tst1
Please provide a full path [q to quit]: tst2
Please provide a full path [q to quit]: tst3
Please provide a full path [q to quit]: tst4
Please provide a full path [q to quit]: q
File does not exist File does not exist File does not exist File does not exist Exiting..
[root@tsting:0]#

I’m guessing this happens because the loop collapses back printing all the echos as it happens, is there a way to avoid this and just print the echo when the wrong file location is entered ?


Source: bash

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.