Created
August 20, 2021 09:17
-
-
Save omnituensaeternum/297394880828ac5177ba3dc4cf5440f6 to your computer and use it in GitHub Desktop.
Check if a website at URL is up in bash using curl.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# FUNCTION | |
isSiteUp () { check=`curl -Is $1 | head -1 | awk '{print $2}'`;if [ "$check" = "200" ]; then return 1; else return 0; fi; } | |
# EXAMPLE USAGE | |
siteToCheck="https://qrng.anu.edu.au/API/jsonI.php?" #This is a quantum random number api but any url should work. | |
test=`isSiteUp $siteToCheck` | |
if [ "$?" = "1" ];then | |
echo "The website at: [$siteToCheck] is [ONLINE]" | |
else | |
echo "The website at: [$siteToCheck] is [OFFLINE]" | |
fi | |
# Explanation: | |
# The isSiteUp function takes a url as arg 1 and returns 1 if the url returned a 200 status code. | |
# We use curl to achive this. We tell curl to only fetch the headers (-I) in silent mode (-s). (because a loading bar is annoying) | |
# Then we pipe the first header (something like "HTTP/2 200" or "HTTP/1.1 200 OK") into awk to get the status code "200". | |
# If it is 200 then return 1 for success, else return 0 for failure. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please don't crucify me for my shitty bash conventions and syntax. Also this only handles status codes of "200" so if the status is literally anything else when it curl's it then it will say the site is offline. (More info on HTTP status codes)