JCOidl
JCOidl

Reputation: 464

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?

Upvotes: 4

Views: 4623

Answers (3)

fregante
fregante

Reputation: 31779

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

echo "Extra line" | cat - file.txt | the_script

Upvotes: 5

cdarke
cdarke

Reputation: 44394

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.

Upvotes: 3

Stephane Rouberol
Stephane Rouberol

Reputation: 4384

This should do in bash:

{ echo "Here is an extra line of text"; cat file.txt; } < the_script

Upvotes: 0

Related Questions