Preserving argument spacing, etc when passing into

2019-06-24 01:12发布

问题:

I have a shell script that launches a Maven exec:java process -

exec mvn exec:java -Dexec.mainClass=... -Dexec.args="$*"

Now sadly if I run

./myMagicShellScript arg1 "arg 2"

the single string arg 2 doesn't make it through as a single argument as I'd like.

Any thoughts as to how to escape / pass things through properly (perferably in a clean way)?

回答1:

I took a look at the mvn script and did some testing. This is what I came up with:

Try changing your script to look like this:

args=(${@// /\\ })
exec mvn exec:java -Dexec.mainClass=... -Dexec.args="${args[*]}"

That changes all spaces which are within each array element to be escaped with a backslash.