0

I have a simple script that tries to curl and URL and echo a string if it failed or succeeded. But I get the following warnings, depending on how I form this if statement.

Depending on the quotes I use in the statement below I get the following warnings:

: -ne: unary operator expected
: integer expression expected

With the alternative check (as comment), I get the following error

((: != 0 : syntax error: operand expected (error token is "!= 0 ")

The script:

c=`curl -s -m 10 https://example.com` || ce=$?

#if (( ${je} != 0 )); then 
if [ ${ce} -ne 0 ]; then 
        echo "Failed"
else
        echo "Succeeded"
fi

How do I correctly check the return value of the curl command in a bash if-statement?

1 Answer 1

2

The problem is that you only set the exit status when the curl command fails. If the command succeeds, then variable ce is not set (and also not quoted) and the test executes if [ -ne 0 ]; then and prints the error message. Quoting the variable alone wouldn't help in this case, you would just get a different error message.

To fix this, set variable ce after the curl command no matter what the exit status of the curl command is:

c=$(curl -s -m 10 https://example.com)
ce=$?
if [ "$ce" -ne 0 ]; then 
  echo "Failed"
else
  echo "Succeeded"
fi

Or shorter without exit status variable:

c=$(curl -s -m 10 https://example.com)
if [ $? -ne 0 ]; then 
  echo "Failed"
else
  echo "Succeeded"
fi
Sign up to request clarification or add additional context in comments.

1 Comment

Even shorter: if ! c=$(curl ...); then

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.