How to Build an If Condition in Shell to Check Whether Curl Succeeded

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

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 failure:

if curl -sL --fail http://google.com -o /dev/null; then
echo "Success"
else
echo "Fail"
fi

How can I verify curl response before passing to bash -s?

Without a user-managed temporary file:

if script=$(curl --fail -sSL "$url"); then
bash -s <<<"$script"
fi

How to check if an URL exists with the shell and probably curl?

Using --fail will make the exit status nonzero on a failed request. Using --head will avoid downloading the file contents, since we don't need it for this check. Using --silent will avoid status or errors from being emitted by the check itself.

if curl --output /dev/null --silent --head --fail "$url"; then
echo "URL exists: $url"
else
echo "URL does not exist: $url"
fi

If your server refuses HEAD requests, an alternative is to request only the first byte of the file:

if curl --output /dev/null --silent --fail -r 0-0 "$url"; then

If/Else curl command not working

As you seem in need of a "one-liner", here is the same idea, but embedded inside of an if/else block.

if (( $( curl $WEBSITEURL | grep -c "incident-title" ) > 0 )) ; then printf "Investigating Issue"; else printf "Fully Operational"; fi

IHTH

Using an if statement with curl in terminal?

You can store the result in a shell variable (via command substitution), and then test the value with a simple if and [[ command. For example, in bash:

#!/bin/bash
code=$(curl -s -o /dev/null -w "%{http_code}" 'https://www.example.com')
if [[ $code == 200 ]]; then
rm /path/to/file
# other actions
fi

If all you want is a simple rm, you can shorten it to:

#!/bin/bash
[[ $code == 200 ]] && rm /path/to/file

In a generic POSIX shell, you'll have to use a less flexible [ command and quote the variable:

#!/bin/sh
code=$(curl -s -o /dev/null -w "%{http_code}" 'https://www.example.com')
if [ "$code" = 200 ]; then
rm /path/to/file
fi

Additionally, to test for a complete class of codes (e.g. 2xx), you can use wildcards:

#!/bin/bash
[[ $code == 2* ]] && rm /path/to/file

and the case command (an example here).

How to evaluate http response codes from bash/shell script?

I haven't tested this on a 500 code, but it works on others like 200, 302 and 404.

response=$(curl --write-out '%{http_code}' --silent --output /dev/null servername)

Note, format provided for --write-out should be quoted.
As suggested by @ibai, add --head to make a HEAD only request. This will save time when the retrieval is successful since the page contents won't be transmitted.



Related Topics



Leave a reply



Submit