Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple layers of quotes in bash

Tags:

linux

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?

like image 550
abelenky Avatar asked Dec 29 '11 21:12

abelenky


People also ask

How do you double quotes in bash?

A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ' ! ' appearing in double quotes is escaped using a backslash. The backslash preceding the ' !

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

Can you have multiple if statements in bash?

Bash else-if statement is used for multiple conditions. It is just like an addition to Bash if-else statement. In Bash elif, there can be several elif blocks with a boolean expression for each one of them. In the case of the first 'if statement', if a condition goes false, then the second 'if condition' is checked.

What is the difference between && and || in bash?

Save this answer. Show activity on this post. && and || are boolean operators. && is the logical AND operator, and bash uses short cut evaluation, so the second command is only executed if there is the chance that the whole expression can be true.


2 Answers

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[@]}"
like image 71
user1686 Avatar answered Sep 19 '22 12:09

user1686


try this:

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

you can espape using '' and \"

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

like image 24
El David Avatar answered Sep 21 '22 12:09

El David