循环查找文件位置,直到文件存在于bash中 [英] loop for file location until file exists in bash
问题描述
我已经创建了此功能:
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
一切正常,除非有人写了错误的文件位置,否则直到有人单击q或输入现有文件位置后,回显才会显示. 在这种情况下,将显示回显消息*错误输入的数量,如下所示.
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 ?
推荐答案
将错误写入stderr
Write the error to stderr
echo "File does not exist, please try again" >&2
您会将函数的所有输出保存到变量tempLoc
中,因此,即使用户输入了有效文件,该变量也会在其中带有大量垃圾.
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还是应该出现错误消息的地方,因此,即使没有这个问题,将错误消息发送到那里也是一个好习惯.
Stderr is where error messages should go anyway though, so it's good practice to send them there even without this problem.
这篇关于循环查找文件位置,直到文件存在于bash中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!