We know that it's simple to send the contents of a text file, file.txt
, to a script that reads from standard input:
the_script < file.txt
Supposed that I'd like to do the same thing as above, except I have an extra line of text I'd like to send to the script followed by the contents of the file? Surely there must be a better way than this:
echo "Here is an extra line of text" > temp1
cat temp1 file.txt > temp2
the_script < temp2
Can this be accomplished without creating any temporary files at all?
Building on cdarke's answer to make it readable left-to-right:
echo "Extra line" | cat - file.txt | the_script
There are several ways to do this. Modern shells (Bash and ksh93) have a feature to support reading a single value from stdin, known as a here string:
cat - file.txt <<< "Extra line"|the_script
The first argument of cat
is a hyphen -
which reads from standard-input. The here string follows the <<<
notation.
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