循环查找文件位置,直到文件存在于 bash 中 [英] loop for file location until file exists in bash

查看:24
本文介绍了循环查找文件位置,直到文件存在于 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆