You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash select语句与文件行循环读取的输入冲突问题及解决

Bash中select语句与文件行读取的冲突问题及解决方法

意外的是,我未找到关于Bash select语句结合文件行循环读取的特定场景案例。实际运行时发现,select语句不会阻塞等待用户输入,而是自动读取文本文件中的换行符。

简化示例代码

#!/bin/bash
# test.sh

confirm() {
    local value=${1}
    echo "Confirm '${value}'?"
    select ans in Yes No; do
        case ${ans} in
            Yes ) break ;;
            No ) echo "Bye!" ; return 1 ;;
        esac
    done
}


cat <<EOF > lines.txt
one
two
three
EOF

while read line; do
    confirm ${line} || exit 1
done < lines.txt

rm -f lines.txt

运行输出(无需等待用户输入直接执行完成)

$ ./test.sh
Confirm 'one'?
1) Yes
2) No
#? #? #?

bash版本:5.1.8(来自RHEL 9.2)

显然这是因为select默认从stdin读取输入,与文件内容读取的输入源产生冲突。若让select显式从终端读取,即可正常运行:

...
confirm() {
    local value=${1}
    echo "Confirm '${value}'?"
    select ans in Yes No; do
        case ${ans} in
            Yes ) break ;;
            No ) echo "Bye!" ; return 1 ;;
        esac
    done </dev/tty # 显式从终端读取输入
}
...

我也曾尝试将文件读取定向到其他描述符,但结果依旧相同:

...
exec 6< lines.txt
while read line; do
    confirm ${line} || exit 1
done <&6
...

希望有人能解释该现象的原因,以及处理此类输入源冲突的标准方法。感谢!


编辑更新

感谢Gordon、Will和Charles的建议!参考相关回答后,我做了如下修改,运行符合预期:

...
while read line <&6; do
    confirm ${line} || exit 1
done 6< lines.txt
...

内容的提问来源于stack exchange,提问作者jlearmond

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 04:06:32