Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

i'm writting a script that will backup data from my laptop to an ubuntu server. to do so, i'm looking for a (ba)sh command to test if the server is available before starting the backup. something like "ping" on port 22 that returns a boolean

how can i do this ? thanks for helping

share|improve this question
up vote 10 down vote accepted

Like this:

nc -z hostname 22 > /dev/null
echo $?

If it's 0 then it's available. If it's 1 then it's not.

share|improve this answer

Use netcat:

nc -z localhost 22

From the manpage

 -z      Specifies that nc should just scan for listening daemons,
         without sending any data to them.
share|improve this answer
Damn! You beat me to it. – bahamat Feb 2 '11 at 20:23
thanks, didn't know nc , i was wondering why nc -z -w 2 ( -w is the timeout option, in seconds ) does not timeout :| – Amo__ Feb 2 '11 at 23:12
You need to specify a port too. nc -z -w 2 22 works as expected. – chris Feb 3 '11 at 7:36

What about

exec 3>/dev/tcp/${MACHINE}/22
if [ $? -eq 0 ]
    echo "SSH up"
    echo "SSH down"
share|improve this answer
Don't always assume that it's Linux. His laptop may be a Mac. And Debian disables /dev/tcp. Ubuntu being Debian derived may as well (but I have no specific knowledge). But if /dev/tcp is available, then yes this is perfectly valid. – bahamat Feb 2 '11 at 20:35
thx for your feedback, i've wrote it on a Mac. – user4418 Feb 2 '11 at 20:49
thanks, even if exec 3>/dev/tcp/${HOST}/22 looks really "bizarre" – Amo__ Feb 2 '11 at 23:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.