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 ?
Write the error to stderr
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.