I have simple bash nc script:

nc -k -l 4444 > filename.out

which listens 4444 port for TCP connection. Instead of redirecting received data to filename.out I would like, if possible, to pass each chunk of data (single lines of text) to script.sh as argument. How do I do that?

Thanks in advance.

EDIT: I've also tried with:

nc -k -l 4444 | /path/to/script.sh

but that doesn't work

  • What does "doesn't work" mean? nc -k -l 4444 | perl -nle 'print if m/foo/' prints only input lines containing foo for me. – thrig Mar 17 '16 at 21:01
  • @thrig good question. /path/to/script.sh is bash script that should echo $1 > result.txt - fill txt file with $1 argument which it does not. – Miloš Đakonović Mar 17 '16 at 21:07
  • $1 is the first argument to the script, which is not set in your example. nc instead passes the input on standard input, so read it with a while read line; do ...; done loop or cat or something. – thrig Mar 17 '16 at 21:14
  • You also might look at inter-process communication using Bash, one example being at stackoverflow.com/questions/10862970/… . And here is another utilizing FIFOs linuxjournal.com/content/using-named-pipes-fifos-bash – Thomas N Mar 17 '16 at 21:26

This below is the entry point to a multi-input script.

[ $# -ge 1 -a -f "$1" ] && input="$1" || input="-"

# your script's payload here

The #! line is self explanatory I hope

on the second line

$# -ge 1 and is testing for at least one command line argument

-a is the boolean and operator

-f "$1" is testing if the first argument is a file

&& is followed by the directive to be executed if the previous condition holds true

|| is followed by what happens if the test condition is not true

nc -k -l 4444 > filename.out
my_processing_script filename.out


nc -k -l 4444 | my_processing_script

so, if I have an argument and it is a file, my input is this file, if not, my input is coming from the pipe, i.e. "-"

then you can run your thing as you wish. Either

I tested with payload of

awk '{print $2}' ${input}

and my input was coming from netstat -rn command and worked either way. I hope this is what you are asking about

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.