#!/bin/bash # Author: see http://bashcurescancer.com/improve-this-script-win-100-dollars.html # Improve and send to me function httpClient() { URL=$1 if [ $# -ne 1 ] then echo "Usage: `basename $0` url" exit 1 elif echo $URL | egrep -q '^http://' # url must start with http then oldIFS=$IFS IFS=/ set -- $URL HOST=$3 # Get the host RESOURCE="" shift 3 while [ $# -gt 0 ] do RESOURCE="$RESOURCE/$1" # Get the resouce shift done IFS=$oldIFS if [ -z $RESOURCE ] || echo $URL | egrep -q '/$' # If empty or url ends in /, add / then RESOURCE="$RESOURCE/" fi exit if ! ping -c 1 -q $HOST 2>&1 >/dev/null # Make sure its on the network. What if not # accepting pings? Maybe we don't even care. # Not sure how bash responds when the host # is not reachable then echo "$HOST not found" exit 1 fi else echo "$URL not a valid URL. Must start with http://" exit 1 fi exec 3<> /dev/tcp/$HOST/80 # Open connection echo "GET $RESOURCE HTTP/1.1" 1>&3 # Request resource, only care about gets. echo "host: $HOST" 1>&3 # Send host header, what about encoding? echo 1>&3 # End request BODY=1 # Headers are done flag HEADERS="" # Store headers, maybe use later TIMEOUT=30 # After initial connection we will only wait 1 second for timeout while true do read -u 3 -t $TIMEOUT REPLY || break # read from server or be done with it LINE=$( echo $REPLY | tr -d '\r' ) # Eliminate \r, we are using UNIX if [ $BODY -eq 0 ] then echo "$LINE" # If after headers, print elif echo $LINE | egrep -q '^$' then BODY=0 # End of headers TIMEOUT=1 # Read takes a long to die after the connection is done, make # it timeout after 1 second after the server is giving us data else HEADERS="$HEADERS\n$LINE" # Save headers, for no reason fi done exec 3<&- } httpClient $*