I write a script which sends the input file to CPP, then to grep, then to a certain program:

cpp $1 | grep -v "#" | theprogram

But, "theprogram" requires the input to start with a certain constant line "theprogram-1.0". So, I want to prepend that constant line to the output of grep, just before it is sent to "theprogram".

Of course, I can do all this using a temporary file... but I am sure there is a way to do such a simple task in a single line of shell pipes, without temporary files. What is the trick?


You can surround a sequence of commands with parentheses. Each command inside the parentheses will have access to the same stdin, stdout, and stderr. Here, echo will send to stdout but will not alter the stdin that grep sees.

cpp $1 | (echo 'your constant line here'; grep -v "#") | theprogram

As described in Shell command language: grouping commands, one can use braces instead of parentheses for grouping. Using braces is slightly more efficient, since a subshell won't be created, but it presents more complicated syntax: there needs to be a field separator after the {, and a delimiter such as ; or newline before the }. But several people have suggested it as an alternative, so here it is:

cpp $1 | { echo 'your constant line here'; grep -v "#"; } | theprogram
  • You don't need a subshell here, just use a command group. – Chris Down Jan 20 '14 at 6:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.