Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

unix

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

like image 675
Palace Chan Avatar asked Dec 20 '22 17:12

Palace Chan


2 Answers

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

like image 64
Maxim Egorushkin Avatar answered Jan 06 '23 10:01

Maxim Egorushkin


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.

like image 35
glenn jackman Avatar answered Jan 06 '23 11:01

glenn jackman