I'm trying to understand what grep -v grep
does below:
ssh $server -p $port -o "ConnectTimeout 5" | grep -v "Connection refused" | grep "Connected to" | grep -v grep | wc -l
Or is there a better way to find TCP connection test?
If you want to check that you can establish a ssh connection within 5 seconds and run a command, just do:
if ssh -o BatchMode=yes -o ConnectTimeout=5 -p "$port" "$server" true; then
printf '%s\n' "$server is up"
fi
Your command as it is makes little sense. As you don't provide with a command to run on the remote server, ssh
will run in the rlogin
mode, where a pseudo-terminal is requested and the login shell of the remote user is started (or possibly a ForcedCommand).
Then, you're applying several filters to the output:
grep -v "Connection refused"
: filter out any line from the output that contains Connection refused
. That makes little sense as that error message if it appeared would be written on stderr, not the standard output that grep
is filtering, and also because:grep "Connected to"
: select only the lines that contain Connected to
. That would also exclude the lines that contain Connection refused
as it's unlikely for a line to contain both.grep -v grep
, also remove the lines that contain grep
(so that would be lines that contain both Connected to
and grep
and not Connection refused
!)wc -l
: count the number of resulting lines (so the lines in ssh
's stdout that contain Connected to
except those that also contain grep
or Connection refused
). Note that wc
will only output that number when the connection is closed, when the shell session has been terminated, like when the user enters exit
. But then again, since the user won't see any output (since it all goes to wc
eventually), the user will have little clue that he needs to enter exit
to terminate that session. It excludes all lines containing the letter sequence grep
from the previous pipe output.
man grep