I want to write a shell script that accepts data from standard input, write it to a file and then does something with it.
For the purpose of this question, let us assume, that my script should accept standard input, write it to in.txt
, then grep a string "foo"
from it and write the output to out.txt
.
I wrote this script.
cat > in.txt
grep foo in.txt > out.txt
As explained in some of the answers below, one could just use
tee in.txt | grep foo > out.txt
What if it is some other command instead of grep
that does not read from standard input? Does it become a valid use of cat then?
Here is one such example with chmod
.
cat > in.txt
chmod -v 600 in.txt > out.txt
It is a requirement that both the input and the output must be available in files after the script ends.
I would like to know if my code is making a useless use of cat
or if this is a perfectly valid scenario when cat
may be invoked like this?
Also, is there a way to rewrite this code without using cat
such that it does not make a useless use of any command?
Note: I am concerned with answers that applies to any POSIX compliant shell, not just Bash or Linux.
Its a valid use of cat
but the tee
command is what you want. Its designed to write everything to a file and to stdout.
tee in.txt | grep foo > out.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With