Issue
I need 4 things from curl in a BASH script:
- I need to capture brief humanly readable error message from curl into a bash variable.
- I need to be able to check that the command completed successfully or not.
- I need the command to run
- I don't want anything printed to console unless I echo it.
m=$(curl -u "$user":AP"$pass" -T "$pathA" "$url") if [ $? -ne 0 ] ; then echo "Error: ""$m" fi
The problem is curl puts gibberish into $m. It just dumps the error to console instead of m. I don't want anything printed to console unless I echo it. And I only want to capture error descriptions. I tried many variations, nothing seemed to work for this use-case... at least nothing suggested here on Stack.
Solution
curl
sends errors to STDERR and will not get captured by $m
. The output of curl
is sent to STDERR (that gibberish you mentioned).
One solution is to redirect STDERR to STDOUT by adding 2>&1
to your curl
invocation in your script:
m=$(curl -u "$user":AP"$pass" -T "$pathA" "$url" 2>&1)
if [ $? -ne 0 ] ; then
echo "Error: ""$m"
fi
You could also use the --fail
, --silent
and --show-errors
flags of curl
like in this example if all you care about are the errors:
Making curl send errors to stderr and everything else to stdout
and some information about capturing STDERR to $variable
in bash scripts:
Bash how do you capture stderr to a variable?
Answered By - oaccamsrazor Answer Checked By - Robin (WPSolving Admin)