Uses cat to read data from standard input and writes it to a file, rather than useless use of a cat?

I want to write a shell script that takes data from standard input, writes it to a file, and then does something with it.

For this question, suppose my script should accept standard input, write it to in.txt , then output the 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, you could simply use

 tee in.txt | grep foo > out.txt 

What if this is some other command instead of grep that cannot be read from standard input? Does it become actual use of the cat then?

Here is one such example with chmod .

 cat > in.txt chmod -v 600 in.txt > out.txt 

The requirement that entry and exit be available in the files after the script completes.

I would like to know if my code uses useless use of cat , or if it is a perfectly valid scenario when cat can be called like this:

Also, is there a way to rewrite this code without using cat so that it doesn't make useless of any command useless?

Note. I'm interested in answers that apply to any POSIX compatible shell, not just Bash or Linux.

+5
source share
2 answers

Its actual use is cat , but the tee command is what you want. It is designed to write the entire file to standard output.

 tee in.txt | grep foo > out.txt 
+4
source

The purpose of cat is to concatenate (or "catenate") files. If this is only one file, without connecting it with anything, it is a waste of time and costs you the process. - era ericsson

So yes, it is de facto useless. tee solution amazes me as the very POSIXy way to do this, but you could deploy shell-specific constructs if the cost of the two processes was too high.

-1
source

Source: https://habr.com/ru/post/1239613/


All Articles