JGK
JGK

Reputation: 4168

Preserve space in value of a variable

When using a sapce in a value of a variable, I always get this value somehow ugly expanded. The code looks like this:

#!/bin/bash

CURL="-H 'Accept: application/json' -s -S"

curl ${CURL} https://api.github.com/feeds

Executing this with bash -x results in:

+ CURL='-H '\''Accept: application/json'\'' -s -S'
+ curl -H ''\''Accept:' 'application/json'\''' -s -S https://api.github.com/feeds
curl: (6) Couldn't resolve host 'application'

Btw I know that space is not necessary, this is just an example. One solution to this problem is to encode the space to \x20 as in

#!/bin/bash

CURL="-H Accept:\x20application/json"

curl ${CURL} https://api.github.com/feeds

This works

+ CURL='-H Accept:\x20application/json'
+ curl -H 'Accept:\x20application/json' https://api.github.com/feeds

but I find this solution is not good readable.

Is there an other way of quoting the space in the value of the variable, so the space remains preserved and the string (value) is good readable?

Upvotes: 0

Views: 43

Answers (1)

chepner
chepner

Reputation: 531858

This is what arrays are for: storing sequences of values that can't easily be embedded or extracted from a single string.

curl_opts=(-H "Accept: application/json")

curl "${curl_opts[@]}" https:/api.github.com/feeds

Upvotes: 4

Related Questions