2

I'm a newbie in bash scripting and I have a problem with the aggrupation of the commands. Precisely in this line of code:

timeout -s 9 1 echo $var | nc localhost port

I'm trying to send data of a variable var via netcat to localhost in a specific port, and I want to timeout that command for 1 second. Reading the man pages of timeout I understand that it should be used as:

timeout -s SIGNAL TIME COMMAND

My question is how to replace COMMAND with the piped command echo $var | nc localhost port and for further knowledge how to write correctly the next situations:

COMMAND1 | (COMMAND2 | COMMAND3)

and

(COMMAND1 | COMMAND2) | COMMAND3

If I'm correct, the second example is equivalent to

COMMAND1 | COMMAND2 | COMMAND3

but I don't know how to write the first one.

  • 2
    You could just do echo "$var" | timeout -s 9 1 nc localhost port That wouldn't solve the overall issue of timing out an entire pipeline though. – jesse_b Feb 1 at 23:11
  • @jesse_b yeah I like this aproach, thank you so much!! – TempledUX Feb 1 at 23:25
  • Do you mean aggregation (or grouping)? – muru Feb 2 at 6:03
  • 1
    For this particular case you don't need a pipeline: timeout -s9 1 nc localhost port <<<$var (unless it contains globs you want expanded, or whitespace to be normalized) – dave_thompson_085 Feb 2 at 7:52
  • @dave_thompson_085 that's a pretty elegant solution, I didn't know about the <<< operator, thank you for the new knowledge!! – TempledUX Feb 2 at 23:48
5

That COMMAND is going to be interpreted by timeout, not bash. You cannot put a subshell (the piped commands inside ( and )).

You could put your commands inside a shell script and then pass its name to timeout.

Or actually force COMMAND to be interpreted by bash. This should work:

timeout -s 9 1 bash -c "echo $var | nc localhost port"
|improve this answer|||||
  • This was the main issue, I thought that the COMMAND was interpreted directly by bash, now I see clearly why it didn't work. Thank you!! – TempledUX Feb 1 at 23:27

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.