With curl
, I do the following to check if a webpage is online:
if curl --output /dev/null --silent --head --fail "${url}"; then
echo "URL exists: ${url}"
else
echo "URL does not exist: ${url}"
fi
However, if the server refuses HEAD
requests (or I don’t know), an alternative is to request only the first byte of the file:
if curl --output /dev/null --silent --fail --range 0-0 "${url}"; then
echo "URL exists: ${url}"
else
echo "URL does not exist: ${url}"
fi
The first case is easy to replicate in Ruby:
require 'net/http'
require 'uri'
uri = URI.parse(url)
response = Net::HTTP.get_response(uri)
if response.kind_of? Net::HTTPOK
puts "URL exists: #{url}"
else
puts "URL does not exist: #{url}"
end
How do I replicate the second curl
case?