2

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.

2
  • 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. Commented Jul 20, 2019 at 0:37
  • That's right -- you should make that an answer so it can be marked correct. Commented Jul 20, 2019 at 0:41

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.