Skip to content
Advertisement

bash hiding default stderr code and replacing it with my own

When I use ping foo.com I either get a response or ping: unknown host foo.com I am using this script to show custom responses

status=$(ping -c 1 foo.com 2> /dev/null)

if [[ status -ne '200' ]]; then
     echo "site found"
    else
     echo "site not found" 
fi

the problem with the above is that, if site is found I get site found response, but if not instead of the error message, I get the default ping: unknown host foo.com

UPDATED.

declare -A websites 
websites=("" "")
    function ping_sites(){
        if [[ $1 != 'all' ]]; then 
            status=$(curl -I  --stderr /dev/null $1 | head -1 | cut -d' ' -f2)
            result=$(ping -c 1 $1 | grep 'bytes from' | cut -d = -f 4 | awk {'print $1'} 2> /dev/null)

            if [[ status -ne '200' ]]; then
                echo -e "$1  $c_red t $status FAIL $c_none"
            else
                echo -e "$1  $c_green t $status OK $c_none"
            fi
        else
          ... 

.

ping all 
ping foo.com

Advertisement

Answer

pingWrap(){
  if ping -c 1 "$1" >/dev/null 2>&1; then
    echo "site found"
  else
    echo "site not found" 
  fi
}
pingWrap foo.com
pingWrap localhost

if ping -c 1 "$1" >/dev/null 2>&1; then suppresses all output and tests the return status of the ping command which is either 0 (success) or something else (failure).

[[ status -ne '200' ]] takes the string status and the string 200, converts each to an integer and tests the two integers for inequality, which is as nonsensical as it sounds.

The return status of a shell command is held in the $? variable and it has nothing to do with HTTP return codes. HTTP runs on top of TCP, and ping doesn’t even use TCP.


HTTP Statuses

If the target site is up and speaks HTTP, you can get the http status on stdout with:

httpStatus(){ curl -s -w %{http_code} "$@" -o /dev/null; }

E.g.,

httpStatus google.com #200
httpStatus google.com/secret #301

st="`httpStatus "$1"`" &&
case "$st" in
   301) echo Moved permanently;;
   200) echo Success;;
     *) echo Unknown;;
esac
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement