1

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.

code
  • 1,056
  • 10
  • 22
  • 2
    You are using *command substitution* to capture ALL output from `curl` in `m` except you are not capturing `stderr`. Add `2>&1` at the end of your `curl` command, e.g. `..."$url" 2>&1)` Also `echo "Error: $m"` is sufficient. – David C. Rankin Jul 20 '19 at 00:37
  • That's right -- you should make that an answer so it can be marked correct. – GaryO Jul 20 '19 at 00:41

2 Answers2

4

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?

0

Similar to one suggested; I m just using the output stderror as $? is always 0.

OUTPUT=$(curl -X POST -H 'Content-type: application/json' --data "{\"text\":\"$MSG \"}" $SLACK_URL 2>1)
echo $OUTPUT
if [[ $OUTPUT == "ok" ]]; then
  echo "$FILE_NAME Msg successfully sent"
elif [[ $OUTPUT == "invalid_token" ]]; then
  echo "$FILE_NAME Slack url incorrect"
else
  echo "$FILE_NAME Some issue Sending msg"
fi
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Its not blank
  • 3,055
  • 22
  • 37