Ubuntu 24.04下Bash循环读取用户输入失败的解决方法咨询
问题原因
你的脚本异常是因为while循环通过< "$REMOTE_CONFIG_LIST"将标准输入(stdin)重定向到了目标文件,导致循环内的read命令默认从该文件读取内容,而非等待用户的终端输入。
可行解决选项
选项1:使用自定义文件描述符读取文件
通过自定义文件描述符(如3)绑定目标文件,保留默认stdin指向终端,供用户输入使用。这是Bash的最佳实践,逻辑清晰且无副作用。
修改后的脚本:
#!/bin/bash REMOTE_CONFIG_LIST="./files_to_copy.txt" while IFS=' ' read -r remote_file local_dest <&3 do echo echo "Line = " "$remote_file" "$local_dest" read -p "Please enter your name: " name echo "Hello, $name!" echo done 3< "$REMOTE_CONFIG_LIST"
选项2:强制从终端读取用户输入
在循环内的read命令中,明确指定从终端设备/dev/tty读取输入,绕过当前的stdin重定向。这种方式修改量小,适合快速修复。
修改后的脚本:
#!/bin/bash REMOTE_CONFIG_LIST="./files_to_copy.txt" while IFS=' ' read -r remote_file local_dest do echo echo "Line = " "$remote_file" "$local_dest" read -p "Please enter your name: " name < /dev/tty echo "Hello, $name!" echo done < "$REMOTE_CONFIG_LIST"
选项3:通过管道传递文件内容+终端输入重定向
用cat读取文件并通过管道传递给循环,同时确保用户输入从终端读取。注意:管道会创建子shell,循环内的变量修改无法影响脚本的外部上下文。
修改后的脚本:
#!/bin/bash REMOTE_CONFIG_LIST="./files_to_copy.txt" cat "$REMOTE_CONFIG_LIST" | while IFS=' ' read -r remote_file local_dest do echo echo "Line = " "$remote_file" "$local_dest" read -p "Please enter your name: " name < /dev/tty echo "Hello, $name!" echo done
内容的提问来源于stack exchange,提问作者Daniel Goernert
相关产品推荐
相关产品推荐

