boolean.is.null
boolean.is.null

Reputation: 881

Check return value of command in if bash statement

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?

Upvotes: 0

Views: 947

Answers (1)

Freddy
Freddy

Reputation: 4688

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

Upvotes: 2

Related Questions