问题描述
这个 bash 脚本将 jar 文件的名称连接到一个类路径(变量 CP),在 while 循环中,该值是正确的,但在这个相关问题中描述的在子 shell 中丢失了 Bash 变量范围
This bash script concatenates the names for jar files to a classpath (variable CP), in the while loop the value is correct but is lost in the subshell as descibed in this related question Bash variable scope
#!/bin/bash
CP="AAA"
func() {
ls -1 | while read JAR
do
if [ ! -z "$CP" ]; then
CP=${CP}':'
fi
CP=${CP}${JAR}
done
echo $CP # <-- prints AAA
}
func
我的问题是,由于我无法确定哪个元素将是最后一个,那么如何保存该值.
My question is, since I can't figure out which element will be the last one, how can the value be saved.
我真的需要将当前值(在循环中反复)保存到文件中吗?
Do I actually have to save the current value (repeatedly in the loop) to a file?
一位同事想出了这个运行良好的命令序列
A colleague came up with this command sequence which works well
ls | xargs echo|tr ' ' :
推荐答案
这里的问题是在管道中使用 while
会创建一个子 shell,而子 shell 不能影响其父级.您可以通过几种方式解决此问题.对于您现在正在做的事情,这就足够了:
The issue here is that using while
in a pipeline creates a subshell, and a subshell cannot affect its parent. You can get around this in a few ways. For what you are doing now, this will suffice:
for JAR in *; do
# Your stuff
done
另外要注意的是,你不应该依赖解析ls
Another thing to note is that you shouldn't rely on parsing ls
这还向您展示了避免使用子shell的方法.
This also shows you ways to avoid the subshell.
这篇关于变量值在子shell中丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!