Reputation: 135
I'm using this command to get the response code of a page using curl:
curl -s -o /dev/null -w "%{http_code}" 'https://www.example.com'
If the response code is 200
, then I want to delete a certain file on my computer. If it isn't 200
, nothing should be done.
What's the easiest way to do this?
Upvotes: 4
Views: 7022
Reputation: 18697
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).
Upvotes: 9