abelenky
abelenky

Reputation: 64730

Using multiple layers of quotes in bash

I'm trying to write a bash script, and I'm running into a quoting problem.

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?

Upvotes: 7

Views: 24142

Answers (3)

El David
El David

Reputation: 696

try this:

RANGE='\"-H \"Range: bytes=20-30\"\"

you can espape using '' and \"

no_error=''errors=\"0\"'';

Upvotes: 1

ugoren
ugoren

Reputation: 16451

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?"

Upvotes: 0

grawity_u1686
grawity_u1686

Reputation: 16657

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:

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:

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[@]}"

Upvotes: 18

Related Questions