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.

6
  • 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
    CommentedFeb 1, 2020 at 23:11
  • @jesse_b yeah I like this aproach, thank you so much!!
    – TempledUX
    CommentedFeb 1, 2020 at 23:25
  • Do you mean aggregation (or grouping)?
    – muru
    CommentedFeb 2, 2020 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)CommentedFeb 2, 2020 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
    CommentedFeb 2, 2020 at 23:48

1 Answer 1

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" 
1
  • 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
    CommentedFeb 1, 2020 at 23:27

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.