Unix shell:将目录名称的文件转换为 ':'分离的类路径
我使用 Java5,并且不想在类路径中指向每个 .jar 文件,因此我尝试编写小型 shell 脚本:
find $LIB_DIR -name '*.jar' -print > /tmp/classpath
CP=
cat /tmp/classpath | while read line
do
CP=$CP:$line
done
rm -f /tmp/classpath
但这不起作用 - $CP 变量为空。
因此 $CP 应该是单个字符串,路径由 ':' 分隔
有谁知道这里出了什么问题以及如何正确地将所有文件的行连接到一个字符串?
I use Java5 and I don't want to point each .jar file in Classpath so I've tried to write small shell script:
find $LIB_DIR -name '*.jar' -print > /tmp/classpath
CP=
cat /tmp/classpath | while read line
do
CP=$CP:$line
done
rm -f /tmp/classpath
But this is not work - $CP variable is empty.
As a result $CP should be single string with pathes delimited by ':'
Is anyone knows what is wrong here and how to correctly concatenate all file's lines to one string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的 while 循环位于子 shell 中,因此不会将任何变量传递回主 shell。无论如何,你想做这样的事情:
这将在一行中完成你想要的一切。
Your while loop is in a sub-shell, so no variables will be passed back to the main shell. You want to do something like this anyway:
That'll do what you want all on one line.
问题是 while 循环在单独的 shell 实例中运行,并且其中的局部变量 (
$CP
) 在外壳中不可用。类似的东西
应该有效。但请注意,
$CP
最终以冒号作为第一个字符,因此它需要一些后处理。此外,您应该使用
mktemp
,否则如果有人在/tmp/classpath
放置符号链接,您可能会被欺骗而覆盖文件。The problem is that the while loop runs in a separate shell instance and the local variable in it (
$CP
) isn't available in the outer shell.Something like
should work. But note that
$CP
ends up with a colon as first character then so it needs some post-processing.Moreover you should make use of
mktemp
otherwise you could be tricked into overwriting files if someone puts a symlink at/tmp/classpath
.为了明确起见,Uwe Kleine-König 和 Steve Baker 所说的 while-do-done 块本质上不是子 shell,而是因为此代码块中使用了管道
来自 Bash 手册页:“管道中的每个命令都作为单独的进程(即在子 shell 中)执行。”
有关子 shell 的更多信息。
另请参阅关于管道和子外壳的另一个SO答案。
在此处输入链接说明
To make it clear that said Uwe Kleine-König and Steve Baker while-do-done block is not subshell by its nature but because of pipe use in this code block
From Bash man page: "Each command in a pipeline is executed as a separate process (i.e., in a subshell)."
More about subshells.
See also another SO answer about pipe and subshells.
enter link description here