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

Sat*_*ian 4 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"
Run Code Online (Sandbox Code Playgroud)

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

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

che*_*ner 6

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

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
Run Code Online (Sandbox Code Playgroud)

-ubash特定于的,但我注意到您已经在使用另一个bash特定于的功能,-pread. 从标准输入以外的内容读取的 POSIX 方法是IFS= read -r repo <&3(即,将文件描述符 3 复制到此命令的标准输入上)。