LINUX Ping host, Display error on failure

hostslinuxping

I'm writing a bash script to ping a given hostname, and display whether or not the host is active (display a simple message.) Should be easy, but headache instead.
Here is what I have so far:

    echo & echo "DOI (Domain):" &&read input 
    ip=$(ping -c 1 $input | gawk -F'[()]' '/PING/{print $2}') 
    if [ $? -eq 0 ]; then  
        echo "$ip is up";  
    else   
        echo "host is down";  
    fi  
    sleep 60  

Here is the output:
Successful ping (& reply), it responds:

    74.125.226.119 is up

However, upon failure to recieve reply it still responds:

    ping: unknown host google.ccccaa 
    is up

rather than echo "host is down"

Obviously, I have overlooked something. I hate asking questions like this, and I'm sure the answer is already hiding here somewhere, but again I am at a standstill and cannot find what I am looking for. I'm not even really sure what I am looking for.

EDIT: Solved! Thank you kindly for the helpful advice!

Here is the final:

    echo & echo "DOI (Domain):" &&read input    
    output=$(ping -c 1 "$input" 2>/dev/null)  
    if [ $? -eq 0 ]; then  
       ip=$(printf '%s' "$output" | gawk -F'[()]' '/PING/{print $2}'  2>/dev/null )  
       echo "$input ($ip) is up";  
    else  
       echo "Host not found";  
    fi  
    sleep 60  

Best Answer

First, you should add 2>/dev/null to the ping invocation, so that error messages from ping would not be printed to the standard error.

Second, $? in your code will not contain the result you expect, because the return status of a pipeline is the exit status of the last command, which is gawk in your case, and the exit status of ping is just ignored. You could rewrite the code, e.g., like this:

output=$(ping -c 1 "$input" 2>/dev/null)
if [ $? -eq 0 ]; then
    ip=$(printf '%s' "$output" | gawk -F'[()]' '/PING/{print $2}')  
    echo "$ip is up";
else
    echo "host is down";
fi
Related Question