简体   繁体   中英

A bash script written around the nc command. How do I prepend text before each line?

I'm using the nc command in an unusual way. I have two bash scripts that initiate a chat session if two users run them at approximately the same time. These scripts are built around the nc command. I want the stream of text to display a value appended after each carriage return (when the user presses enter).

Here is how the scripts work interactively and collaboratively: On workstation 1, I invoke this: nc -l 44444

On workstation 2, someone else invokes this: nc xxxx 44444 (where xxxx is the IP address of workstation 1)

I can chat away with someone else. Whatever either user types is mirrored to the other terminal. My question: how do I write a bash script to append text? I have the text I want in a variable (eg, "said user1").

I want this to be displayed automatically (without the users manually typing it in).

If user on workstation 1 (with IP addresss xxxx) during the chat session types "this is just a test" and presses enter, I want this to be the result:

this is just a test said user1.

If user on workstation 2 (with IP addresss yyyy) during the chat session types "oh, ok" and presses enter, I want this to be the result:

oh, ok said user2.

The user names are in variables in the scripts. I can construct the string without a problem. I just don't know how to get this variable string to display automatically. Can it some text be displayed every time enter is pressed only when the scripts are running? The stream of text is mirrored when a bash script is running. I'm not sure how to accomplish this.

Try this:

sed -u "s/$/said user2 /" | nc xxx.xxx.xxx.xxx 44444
sed -u "s/$/ said user1 /" | nc -l 44444

When nc is running interactively (ie running as a foreground job), its standard input is connected to the terminal, and Bash can't just send input to it too. IMHO, the easiest approach would be to (for each line) read the input in Bash and add the suffix there, then pipe both of it to a new invocation of nc .

Keep in mind that nc will ignore end-of-file (EOF) when reading from standard input, see nc(1) . The -q option tells nc to close the connection after EOF on the client side, and you could just run nc -l in a loop on the server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM