通过外壳传递以空格分隔的系统属性 [英] Passing a space-separated System Property via a shell
问题描述
我很难从使用嵌套变量的shell脚本(bash)启动Java程序。基本上,有许多系统和-D Java属性需要传递给Java程序。我想将它们更好地组织起来,因为它们在一行中很难阅读。
I'm having difficulties to startup a java program from a shell script (bash) where nested variables are used. Basically there are many system and -D java properties that need to be passed to a java program. I would like to organise them in a nicer way one below another as they are very difficult to read when in one line.
这类似于
< a href = https://stackoverflow.com/questions/8214392/passing-a-space-separated-system-property-via-a-shell-script-doesnt-work>通过传递空间分隔的系统属性shell脚本不起作用,但不一样。
这里是精简示例。想象这样的Java程序:
Here is a stripped down sample. Imagine a java program like this:
public class Main {
public static void main(String[] args) {
for (String s : args) {
System.out.println(s);
}
}
}
当这样调用时:
java Main First_Line第二行带有空格
它将给出如下所示的OK结果:
It will give OK result like this response:
First_Line
Second line with spaces
但是是否使用了这样的脚本:
However if script like this is used:
#!/bin/sh
PARAM01="FirstLine"
PARAM02="Second line with spaces"
PARAMS="$PARAM01 $PARAM02"
java Main $PARAMS
然后全部空格被占用,第二个参数未加引号传递给java。结果如下所示:
Then all spaces are eaten and second parameter is passed unquoted to java. Result looks like this:
FirstLine
Second
line
with
spaces
试图用不同的方式引用变量在shell脚本中,但到目前为止没有成功。
Have tried to differently quote variables in a shell script, but so far without success. How to quote shell variables so that spaces are preserved and parameter is passed intact to java?
推荐答案
如果在shell变量上加引号,则如何引用shell变量,以便保留空格并将参数完整地传递给java?命令行 unquoted ,然后进行分词。为了防止单词分裂,请将每个参数都放在双引号中:
If you put a shell variable on the command line unquoted, then it undergoes word splitting. To prevent that word splitting, keep each parameter in double-quotes:
java Main "$PARAM01" "$PARAM02"
或者,如果您想花哨的话,请使用数组:
Or, if you want to get fancy, use an array:
PARAMS=("$PARAM01" "$PARAM02")
java Main "${PARAMS[@]}"
这篇关于通过外壳传递以空格分隔的系统属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!