How to redirect CURL output to file and as bash function parameter
It sounds like you want to use the output of a single command more than once. In that case, you need to store it in a variable, and then use that variable wherever needed. e.g. try something like this:
response="$(curl -H "Accept: application/json" -H "Content-Type:application/json" \
-X POST --data "$data" "$url")"
echo "$response" >> "$LOG"
param=$(json_extract "$jsonkey" "$response")
Another alternative is to use tee
, which sends a command's output to a file as well as to stdout. For example:
param=$(json_extract "$jsonkey" "$(curl -H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data "$data" "$url" | tee -a "$LOG" )")
Personally, I find that using a variable like "$response" leads to more readable and understandable code. Especially when it lets you split very long, complicated one-liners into multiple shorter, easily-understood lines.
skirix
Updated on September 18, 2022Comments
-
skirix almost 2 years
How can I make curl output to
$LOG
and as a second parameter for thejson_extract
function.json_extract
is a function that takes two args. The 'key' and a json string (the output of CURL)param=$(json_extract $jsonkey "$(curl -H "Accept: application/json" \ -H "Content-Type:application/json" \ -X POST --data "$data" $url >> $LOG )")
When I remove the redirect to
$LOG
CURL output is passed as an argument forjson_extract
.-
Alessio almost 5 yearswhat do you mean by "and as a $2 parameter for the json_extract function"? and by "...it works as a parameter?" - what is the "it" you're referring to? and what does "it works" actually mean? there seems to be a lot of context missing from this question.
-
skirix almost 5 years@cas I updated the question.
-
Alessio almost 5 yearsif i'm reading the updated Q correctly, why not run something like:
response="$(curl .....)"; echo "$response" >> "$LOG"; param=$(json_extract "$jsonkey" "$response")
? i.e. if you want to use the output of a command multiple times, store it in a variable and use the variable wherever it is needed.
-
-
skirix almost 5 yearsThank you for the answer ! I used a variable. Like you said, it's more readable