bash - 从文件读取时如何在 while 循环内读取输入?

标签 bash shell terminal

我是 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)

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

最佳答案

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

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 <&3 (也就是说,将文件描述符 3 复制到此命令的标准输入中)。

关于bash - 从文件读取时如何在 while 循环内读取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373633/

相关文章:

ruby - 在一条线上搜索和标记成对模式

linux - bash 脚本中的语法错误 : "(" unexpected -- with ! (*.sh)

linux - 如何编写 cron 以在新终端中显示脚本输出

linux - ./斐波那契.sh : line 11: syntax error near unexpected token `do'

linux - 文本文件中的单引号完整路径文件无法执行 for 循环处理 mv : cannot stat . .. 没有这样的文件或目录

c++ - 如何创建控制台终端?

c - 为什么箭头键会弄乱标准输出?

Bash 变量作用域

bash - 使用 Bash 对三个最新文件进行 scp

linux - Sed 从文件底部开始搜索和追加