Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build an if condition in shell to check whether curl succeeded?

I am running a cURL command in Linux that is returning 200.

curl -sL -w "%{http_code}" "http://google.com" -o /dev/null

However, If I run the same as below, I get "Fail" as output:

if [ "curl -sL -w "%{http_code}" "http://google.com" -o /dev/null" == "200" ]; then echo "Success"; else echo "Fail"; fi

Please let me know that what is wrong here?

like image 310
Moose Avatar asked Sep 10 '25 00:09

Moose


1 Answers

You are not using command substitution correctly. Rewrite it this way:

if [ "$(curl -sL -w '%{http_code}' http://google.com -o /dev/null)" = "200" ]; then
    echo "Success"
else
    echo "Fail"
fi

As Charles suggested, you can further simplify this with --fail option, as long as you are looking for a success or a failure:

if curl -sL --fail http://google.com -o /dev/null; then
    echo "Success"
else
    echo "Fail"
fi
like image 155
codeforester Avatar answered Sep 13 '25 01:09

codeforester