在bash中的引号内转义引号

时间:2017-01-13 11:17:08

标签: bash

我想用包含带引号的字符串的参数扩展现有的环境变量JAVA_OPTS

-XX:OnOutOfMemoryError="echo Killing the process because of the OutOfMemoryError.; kill -9 %p"

我尝试使用反斜杠转义引号:

#!/bin/bash
JAVA_OPTS="$JAVA_OPTS -XX:OnOutOfMemoryError=\"echo Killing the process because of the OutOfMemoryError.; kill -9 %p\""
exec java $JAVA_OPTS -jar /somejar.jar "$@"

但这似乎不起作用,因为我收到以下错误消息:

Error: Could not find or load main class Killing

我怎样才能正确转义引号?

这也不起作用:

JAVA_OPTS="$JAVA_OPTS "'-XX:OnOutOfMemoryError="echo Killing the process because of the OutOfMemoryError.; kill -9 %p"'

更新

我现在如何测试。

printf "%s\n" abc -XX:OnOutOfMemoryError="echo Killing the process because of the OutOfMemoryError.; kill -9 %p"

给予:

abc
-XX:OnOutOfMemoryError=echo Killing the process because of the OutOfMemoryError.; kill -9 %p

预期。

到目前为止,所有其他变体尝试都会提供更多行:

string="abc"
string="$string"$" -XX:OnOutOfMemoryError=\"echo Killing the process because of the OutOfMemoryError.; kill -9 %p\""
printf "%s\n" $string

结果:

abc
-XX:OnOutOfMemoryError="echo
Killing
the
process
because
of
the
OutOfMemoryError.;
kill
-9
%p"

也尝试过:

string="abc"
string=$"$string -XX:OnOutOfMemoryError=\"echo Killing the process because of the OutOfMemoryError.; kill -9 %p\""
printf "%s\n" $string

也尝试过:

string="abc"
string="$string "'-XX:OnOutOfMemoryError="echo Killing the process because of the OutOfMemoryError.; kill -9 %p"'
printf "%s\n" $string

效果相同

1 个答案:

答案 0 :(得分:2)

首先:你不能通过在变量的值中添加引号,转义或类似内容来控制单词拆分(即变量的值如何被拆分为"单词") 。当shell解析命令行时,它会在扩展变量之前解析引号和转义符,因此,当变量中的引号/转义是命令的一部分时,它们为时已晚,无法达到预期的效果。净结果:如果变量引用是双引号,则根本不会进行单词分词;如果它不是双引号,它将在每个空白字符处被分割,无论引号/转义/它们周围是什么。

但是,如果您控制变量的使用方式,则可以使用数组。您可能不应该将其称为JAVA_OPTS,因为它是一个标准名称,并且不应该是一个数组。但你可以这样做:

java_opts_array=(-XX:OnOutOfMemoryError="echo Killing the process because of the OutOfMemoryError.; kill -9 %p")
exec java $JAVA_OPTS "${java_opts_array[@]}" -jar /somejar.jar "$@"

或者,滚动JAVA_OPTS值,如下所示:

java_opts_array=($JAVA_OPTS -XX:OnOutOfMemoryError="echo Killing the process because of the OutOfMemoryError.; kill -9 %p")
exec java "${java_opts_array[@]}" -jar /somejar.jar "$@"