【问题标题】:How to read input inside a while loop while reading from a file?从文件读取时如何在while循环中读取输入?
【发布时间】:2017-09-22 21:44:58
【问题描述】:

我对 bash 脚本非常陌生,这就是我正在尝试做的事情:

1 - 读取文件 - 此文件是名称列表 2 - 询问用户是否要删除 {name} 3 - 如果用户输入 y,则继续

这是我的脚本到目前为止的样子:

while IFS= read -r repo 
    do
        read -p "Do you want to delete $repo" ip 
        echo $ip
        if [ "$ip" == "y" ]
            then
            #do something
        fi

    done < "$filename"

read -p 行不等待用户提示。我有点理解问题出在哪里/在哪里,我试图通过阅读此链接来解决它 - https://bash.cyberciti.biz/guide/Reads_from_the_file_descriptor_(fd)

但不知何故,我无法解决这个问题。我究竟做错了什么?请帮忙!

【问题讨论】:

    标签: bash shell terminal


    【解决方案1】:

    对命名文件使用不同的文件描述符。你知道这些数据来自哪里;你不知道标准输入可能从哪里重定向,所以别管它。

    while IFS= read -r -u 3 repo   # Read from file descriptor 3
    do
        read -p "Do you want to delete $repo" ip   # Read from whatever standard input happens to be
        echo "$ip"
        if [ "$ip" = "y" ]
        then
            #do something
        fi 
    done 3< "$filename"  # Supply $filename on file descriptor 3
    

    -ubash 特定的,但我注意到您已经在使用另一个 bash 特定功能,-p 选项到 read。从标准输入以外的其他内容读取的 POSIX 方法是 IFS= read -r repo &lt;&amp;3(也就是说,将文件描述符 3 复制到此命令的标准输入)。

    【讨论】:

    • 非常感谢!我完全错过了“3”部分!然后我在开始时将其定义为exec 3&lt; $filename,它成功了! :)
    • 如果不需要保持文件打开更长时间,我会保持重定向循环。
    【解决方案2】:

    看到这个问题:

    Does bash support doing a read nested within a read loop?

    本质上,您通过标准输入读取文件,这与您键入时的输入流相同,因此当您提示用户时,脚本会将文件的输入视为用户的输入。如果您改为在另一个输入流上读取文件,则它不会覆盖。

    【讨论】:

    • 是的!我花了一段时间才明白这就是幕后发生的事情。谢谢!
    猜你喜欢
    • 2017-10-12
    • 2018-04-17
    • 1970-01-01
    • 2012-03-30
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    相关资源
    最近更新 更多