如何从命令行处理 MAVEN_OPTS 参数中的 space?

How to handle space in argument in MAVEN_OPTS from the command line?

当有 space,特别是 javaagent 参数时,我在通过 MAVEN_OPTS 向我的 mvn 命令传递参数时遇到了一些问题。我也跟着 this recommendation 双引号分号后的部分但没有运气。

我使用的命令是这样的:

$ export MAVEN_OPTS='-javaagent:"/Users/teras/Library/Application Support/CrossMobile/Plugins/cmxray.jar"'
$ echo $MAVEN_OPTS
-javaagent:"/Users/teras/Library/Application Support/CrossMobile/Plugins/cmxray.jar"
$ mvn -P desktop,run install -B -e
Error opening zip file or JAR manifest missing : "/Users/teras/Library/Application
Error occurred during initialization of VM
agent library failed to init: instrument

不幸的是,这似乎不起作用。如果有帮助,我正在使用 OSX,使用 bash。

知道我错过了什么吗?

恐怕你没那么容易做到。如果你 look at the mvn script 你可以看到它没有把 $MAVEN_OPTS 放在引号里。

所以除非有我不知道的技巧,否则无法逃脱 space。

您可以通过编辑 mvn 脚本在本地修复该问题。如果您使用 homebrew 安装 Maven,您可以在 /usr/local/Cellar/maven/<VERSION>/libexec/bin/mvn 中找到它。制作脚本的副本(这样您可以在出现问题时恢复它)然后在文件末尾找到这些行(根据版本可能会有所不同):

exec "$JAVACMD" \
  $MAVEN_OPTS \
  $MAVEN_DEBUG_OPTS \
  -classpath "${CLASSWORLDS_JAR}" \
  "-Dclassworlds.conf=${MAVEN_HOME}/bin/m2.conf" \
  "-Dmaven.home=${MAVEN_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
  ${CLASSWORLDS_LAUNCHER} "$@"

并在变量周围添加引号,使其看起来像这样:

exec "$JAVACMD" \
  "$MAVEN_OPTS" \
  "$MAVEN_DEBUG_OPTS" \
  -classpath "${CLASSWORLDS_JAR}" \
  "-Dclassworlds.conf=${MAVEN_HOME}/bin/m2.conf" \
  "-Dmaven.home=${MAVEN_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
  ${CLASSWORLDS_LAUNCHER} "$@"

我不确定这是 Maven 错误还是故意这样。看起来像 the issue was reported already,但 Maven 团队似乎有一些反对意见。

更新

看完上面问题的评论后,我发现this one这解释了为什么这毕竟不是一个好的解决方案:

If you quote $MAVEN_OPTS when used here, the java executable will see it as 1 parameter, not multiple ones, so if you have MAVEN_OPTS="-Xmx256m -Dparam=\"with space\"", then java will understand a Xmx value of 256m -Dparam="with space"...

If you don't quote it, then every space separated token (even if it was escaped when declaring MAVEN_OPTS) will be considered a separate argument, so -Dparam="with space" will be understood as trying to launch the space" main class with the -Dparam="with system property...