如何在Bash脚本while循环中用VSCode CLI正确打开多文件?
解决Bash循环中用VSCode CLI批量打开文件的问题
问题根源
你遇到的问题核心是code -参数的用法与标准输入(stdin)的冲突:
code -是VSCode CLI的特殊参数,作用是从标准输入读取内容并创建临时文件打开。- 你的while循环通过
< filenames.txt将脚本的stdin绑定到了filenames.txt,当第一个code命令执行时,它会读取当前stdin中剩余的所有内容(也就是filenames.txt里除第一行外的所有行),进而生成code-stdin-XXX临时文件,打乱了后续循环逻辑。
解决方案
方案1:移除-参数并重定向code的stdin
直接去掉多余的-,同时将code的stdin重定向到/dev/null,避免它读取循环的输入流:
while read -r line ; do code "../songs/$line.xhtml" < /dev/null done < filenames.txt
方案2:使用独立文件描述符读取输入
将循环的输入绑定到额外的文件描述符(比如fd3),让code使用默认stdin,彻底避免流冲突:
while read -r line <&3 ; do code "../songs/$line.xhtml" done 3< filenames.txt
方案3:一次性传递所有文件给code(更高效)
VSCode CLI支持一次性打开多个文件,这种方式既规避了stdin问题,又能提升效率:
# 先收集所有目标文件路径 files=() while read -r line; do files+=("../songs/$line.xhtml") done < filenames.txt # 一次性打开所有文件 code "${files[@]}"
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

