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..
-
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.
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.
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