Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using cat to read data from standard input and write it to a file not a useless use of cat?

Tags:

shell

posix

cat

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.

like image 310
Lone Learner Avatar asked Sep 25 '22 19:09

Lone Learner


1 Answers

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
like image 179
tdelaney Avatar answered Sep 29 '22 05:09

tdelaney