linuxshellif-statementcurl

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?


Solution

  • 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