Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending text plus the contents of a file to standard input, without using temporary files

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?

like image 476
JCOidl Avatar asked Sep 07 '25 11:09

JCOidl


2 Answers

Building on cdarke's answer to make it readable left-to-right:

echo "Extra line" | cat - file.txt | the_script
like image 74
fregante Avatar answered Sep 10 '25 21:09

fregante


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.

like image 41
cdarke Avatar answered Sep 10 '25 22:09

cdarke