变量值迷失在子shell [英] Variables value gets lost in subshell
问题描述
本bash脚本并置的jar文件名到类路径(可变CP),while循环的值是正确的,但在子shell丢失在此相关的问题<一descibed href=\"http://stackoverflow.com/questions/124167/bash-variable-scope\">http://stackoverflow.com/questions/124167/bash-variable-scope
#!/斌/庆典
CP =AAA
FUNC(){
LS -1 |而读JAR
做
如果[! -z$ CP];然后
CP = $ {} CP':'
科幻
CP = $ {CP} $ {} JAR
DONE
回声$#CP&LT; - 打印AAA
}FUNC
我的问题是,因为我不能找出哪些元素将是最后一次,怎么能值被保存。
我是不是真的有(反复循环)的当前值保存到一个文件?
编辑:
一个同事想出了效果很好此命令序列
LS | xargs的回声| TR'':
这里的问题是,在管道中使用,而
创建一个子shell和子shell不能影响它的家长。你可以解决这个问题在几个方面。对于你现在在做什么,这样就足够了:
为JAR的*;做
# 你的东西
DONE
另外要注意的是,你不应该依赖解析 LS
一>
这还显示方式,以避免子shell。
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 http://stackoverflow.com/questions/124167/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?
EDIT:
A colleague came up with this command sequence which works well
ls | xargs echo|tr ' ' :
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
Another thing to note is that you shouldn't rely on parsing ls
This also shows you ways to avoid the subshell.
这篇关于变量值迷失在子shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!