Palace Chan
Palace Chan

Reputation: 9193

use of a bash command to prefix a header to stdout?

I just saw an example on a site which piped the output of an awk command to the following command:

(echo "this is a header";cat -)

This effectively adds the header string at the top of the output..it seems like - represents stdout there. What is this construct though? With a parenthesis, and then cat -? How does this work, this seems quite useful but it's the first time I see it..

Upvotes: 5

Views: 1393

Answers (2)

glenn jackman
glenn jackman

Reputation: 246992

The use of parentheses here is a "Grouping Construct" -- see the details in the bash reference manual

A similar construct uses braces:

{ echo "this is a header"; cat -; }

This is different syntax that requires whitespace around the braces and the trailing semi-colon.

The difference between using braces and parentheses is this: command list in braces runs in your current shell, command list in parentheses runs in a subshell. This is important if you want the command list to alter your environment -- when a subshell exits, environment changes will be lost.

Upvotes: 4

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136365

- often can be use to denote stdin in command line options that accept a file name argument. Note that the effect of cat - is the same as plain cat, i.e. both versions read stdin anyway.

The parenthesis cause the shell to run the commands in a sub-shell. (...) is essentially bash -c '...' if the shell is bash. It is done because in xyz | echo "..."; cat the output of xyz would be piped into echo and lost.

Upvotes: 8

Related Questions