I am using netcat to test if remote exchange server (lets call it exchange1) is online with this code.

nc -w 3 25

I want to create a file that has that servers name if and only if the netcat scan receives a response of '220 SMTP Server Ready', meaning exchange1 is online. If there is no response, I don't want to write the name to the file because it is offline.

  1. What is this called. I believe it to be a type of command result filtering but having trouble finding any articles about how its done.
  2. Can someone provide a simple example of this so I can learn from it.

You can use grep to check of the output of some command matches a pattern, by piping the output of that other command to grep. You use grep inside an if block.

An obviously silly example (and the whole world calls it "Friday", right?):

if date +%A | grep -q 'Friday'; then   # -q tells grep not to echo the matched text
    echo "Nope, sorry, not time yet."

The relevant sections of the Bash manual include "Pipelines" and "Compound Commands".

  • @CaseyMcCarthy There is a checkmark next to the answer you can click to say it solved your problem. You might want to look at the tour for a quick overview of how the site works. – derobert Apr 13 '16 at 21:11
  • Just selected the check, thanks I'll check it out! – Casey McCarthy Apr 14 '16 at 0:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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