0

I've got a scenario where I have command < filename.txt so I can pass the contents of filename.txt and use it in command. But say I want to take the contents out of the file and just use them in one command line action. How would it look?

Say the contents of filename.txt are as follows:

To: [email protected]
Message: Some message

I've tried stuff like command "To: [email protected]\n Message: Some message" with no luck. How do the contents of a text file look when they get parsed into a command in that way?

2 Answers 2

3

In your scenario, command is reading from its standard input; unless it accepts some other way of providing this information, you need to continue feeding it its input in this way. So if you don't want to use a file, use printf with a pipe:

printf "To: [email protected]\nMessage: Some message" | command
2
  • I'm not sure why printf didn't work, but I was able to accomplish the same thing by using echo. Thanks for the idea! May 20, 2015 at 5:10
  • echo sticks a newline at the end of the string by default, while this printf does not. So, I'm betting that command wants a newline. You could add a "\n" at the end of the printf command and I'll bet it would work. :)
    – dannysauer
    Oct 13, 2016 at 18:25
1

New-ish shells like bash and ksh93 support "here documents" and "here strings" if you want literal strings passed in to your command on STDIN. Actually, most shells support here documents.

Here string:

command <<<"some string"

Here document:

command <<END
this will be on
command's STDIN until
an END is encountered by itself
END

The here document uses the thing after the << as the terminator, signaling the end of the document. The terminator has to occur by itself at the beginning of a line. Different shells have slightly fancier possibilities, like optionally removing leading tabs, different quotes on the terminator controlling whether or not variables and shell metacharacters are expanded, etc. Check out your shell's man page for details.

In any event, you can test both of those structure pretty easily by using cat - as the command. I personally find myself using here strings really often.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .