DenCowboy
DenCowboy

Reputation: 15076

Capture output of command which contains quotes and env vars

I know I can capture the output of a bash command like this:

OUTPUT="$(ls -1)"
echo "${OUTPUT}"

But my command itself contains a lot of quotes:

OUTPUT="$(curl -v -u ${USER}:${PASSWD} -X POST -H "Content-Type: application/json" -d '{
"xxx": true,
"xxx2": "date",
...
}' https://${ENV}/${ROOT}/api/try)"

but this returns an empty string:

echo $OUTPUT

How can I capture the output of this command?

Upvotes: 0

Views: 44

Answers (3)

anubhava
anubhava

Reputation: 785058

Just create a function with your complex command:

cmdfn() {
   curl -v -u ${USER}:${PASSWD} -X POST -H "Content-Type: application/json" -d '{
   "xxx": true,
   "xxx2": "date",
   ...
   }' https://${ENV}/${ROOT}/api/try
}

Then call it in command substitution as:

output="$(cmdfn)"

Upvotes: 1

iBug
iBug

Reputation: 37227

Bash handles nested quotes and parentheses very well. This is not the case

OUTPUT="$(curl -v -u ${USER}:${PASSWD} -X POST -H "Content-Type: application/json" -d '{
"xxx": true,
"xxx2": "date",
...
}' https://${ENV}/${ROOT}/api/try)"

It's possible that curl itself is not echoing anything.

Upvotes: 0

Demosthenes
Demosthenes

Reputation: 1535

Two ways, either escape the quotes inside the string with \", or use single quotes, i.e.

% BLA="bla \"a\""
% echo $BLA
bla "a"
% BLA='bla "a"'
% echo $BLA
bla "a"

Upvotes: 0

Related Questions