Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy stdin into two files?

Tags:

bash

io

unix

I need to have script.sh, that would create files f1.txt and f2.txt with content that was sent to stdin. For example:

echo ABRACODABRA | script.sh

...should create files f1.txt and f2.txt with the content ABRACODABRA.

How can I do this?

Please provide script.sh's body!

like image 268
Stepan Yakovenko Avatar asked Jan 16 '23 07:01

Stepan Yakovenko


2 Answers

You need tee.

$ echo 'foo' | tee f1.txt f2.txt 

or

$ echo 'foo' | tee f1.txt > f2.txt

to suppress the additional output to stdout.

I'm guessing your real problem could be how to read from input inside a script. In this case, refer to this question. That will give you something like

while read input; do
    echo $input | tee -a f1.txt > f2.txt
done
like image 87
Lev Levitsky Avatar answered Jan 25 '23 14:01

Lev Levitsky


Your script can look like this:

 #!/bin/bash
 read msg
 echo $msg > f1.txt
 echo $msg > f2.txt
 exit 0
like image 28
joval Avatar answered Jan 25 '23 13:01

joval