将bash逐行读取命令封装到bash -c后仅输出最后一行,缺失什么配置?
问题根因
该问题由Shell变量提前展开导致:
你使用双引号包裹bash -c的命令参数时,双引号内的$first、$second会被当前执行命令的父Shell提前解析替换,而非传递给bash -c启动的子Shell在循环执行时动态赋值。你父Shell环境中残留了之前执行循环时最后一次赋值的first=a4、second="",因此子Shell实际拿到的命令是固定的while read -r first second; do echo first is a4 second is ; done < myfile,最终每行都输出相同的最后一行解析结果。
解决方案
方法1:用单引号包裹bash -c的命令参数(推荐)
单引号内的所有特殊字符都会失去特殊含义,不会被父Shell提前解析,会直接传递给子Shell处理:
bash -c 'while read -r first second; do echo first is $first second is $second; done < myfile'
方法2:双引号内转义$符号
如果你的命令需要引用父Shell的变量、必须使用双引号的场景,可以给子Shell需要动态解析的变量前的$添加反斜杠转义,避免父Shell提前展开:
bash -c "while read -r first second; do echo first is \$first second is \$second; done < myfile"
kubectl exec 适配提示
后续配合kubectl exec使用时,直接将完整命令放入bash -c的单引号参数内即可,示例:
kubectl exec <目标Pod名称> -- bash -c 'while read -r first second; do echo first is $first second is $second; done < /容器内的myfile路径'
内容的提问来源于stack exchange,提问作者Ricky Robinson
相关产品推荐
相关产品推荐

