Linux 在bash中使用多层引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8757163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using multiple layers of quotes in bash
提问by abelenky
I'm trying to write a bash script, and I'm running into a quoting problem.
我正在尝试编写一个 bash 脚本,但遇到了引用问题。
The end result I'm after is for my script to call:
我追求的最终结果是让我的脚本调用:
lwp-request -U -e -H "Range: bytes=20-30"
My script file looks like:
我的脚本文件如下所示:
CLIENT=lwp-request
REQ_HDRS=-U
RSP_HDRS=-e
RANGE="-H "Range: bytes=20-30"" # Obviously can't do nested quotes here
${CLIENT} ${REQ_HDRS} ${RSP_HDRS} ${RANGE}
I know I can't use nested-quotes. But how can I accomplish this?
我知道我不能使用嵌套引号。但是我怎样才能做到这一点?
采纳答案by user1686
Normally, you could escape the inner quotes with \
:
通常,您可以使用以下命令转义内部引号\
:
RANGE="-H \"Range: bytes=20-30\""
But this won't work when running a command – unless you put eval
before the whole thing:
但这在运行命令时不起作用 - 除非你eval
在整个事情之前加上:
RANGE="-H \"Range: bytes=20-30\""
eval $CLIENT $REQ_HDRS $RSP_HDRS $RANGE
However, since you're using bash, not sh, you can put separate arguments in arrays:
但是,由于您使用的是 bash 而不是sh,您可以在数组中放置单独的参数:
RANGE=(-H "Range: bytes=20-30")
$CLIENT $REQ_HDRS $RSP_HDRS "${RANGE[@]}"
This can be extended to:
这可以扩展为:
ARGS=(
-U # Request headers
-e # Response headers
-H "Range: bytes=20-30" # Range
)
$CLIENT "${ARGS[@]}"
回答by ugoren
You can use the fact that both '' and "" can be used for strings.
So you can do things like this:
您可以使用 '' 和 "" 都可以用于字符串的事实。
所以你可以做这样的事情:
x='Say "hi"'
y="What's up?"
回答by El David
try this:
尝试这个:
RANGE='\"-H \"Range: bytes=20-30\"\"
范围='\"-H \"范围:字节=20-30\"\"
you can espape using '' and \"
你可以使用 '' 和 \" espape
no_error=''errors=\"0\"'';
no_error=''errors=\"0\"'';