Some more food for thought : Use nmap or nc, never ping. 
Ping: Why should you not use ping ? (1) It is better to check the system and the port at the same time. (2) Ping is unreliable as icmp echo is blocked in many situations. 
Nmap: This is very quick, very reliable but requires nmap to be installed
Preferred method NMAP (ex host ip 127.0.0.1) :
nmap 127.0.0.1 -PN -p ssh | grep open
Nc: nc is usually installed already , however on some systems such as Mac OS X, the command hangs on unreachable systems. (see workaround) 
nc -v -z -w 3 127.0.0.1 22 &> /dev/null && echo "Online" || echo "Offline"
Mac OSX Workaround :
bash -c '(sleep 3; kill $$) & exec nc -z 127.0.0.1 22' &> /dev/null
echo $?
0
bash -c '(sleep 3; kill $$) & exec nc -z 1.2.3.4 22' &> /dev/null
echo $?
143
(examples illustrate connecting to port 22 ssh over a good and bad host example, use the $? to determine if it reached the host with the sleep time of 3 seconds) 
For Mac Users (mainly) etc, you can use the command in the script like so :
    # -- use NMAP, if not avail. go with nc --
    if command -v nmap | grep -iq nmap ; then
        nmap ${ip} -PN -p ${ssh_port} | grep -iq "open"
        res=$?
    elif command -v nc | grep -iq nc ; then
        # -- run command if fails to complete in 3 secs assume host unreachable --
        ( nc -z ${ip} ${ssh_port} ) & pid=$!
        ( sleep 3 && kill -HUP $pid ) 2>/dev/null & watcher=$!
        if wait $pid 2>/dev/null; then
            pkill -HUP -P $watcher
            wait $watcher
            # -- command finished (we have connection) --
            res=0
        else
            # -- command failed (no connection) --
            res=1
        fi
    else
        echo "Error: You must have NC or NMAP installed"
    fi
    if [[ ${res} -lt 1 ]] ;then
        success=1
        echo "testing  => $ip SUCCESS connection over port ${ssh_port}"
        break;
    else
        echo "testing => $ip FAILED connection over port ${ssh_port}"
    fi