2

I have a command-line program which takes input from stdin. What's the best way for me to pass a line of stdin into that program using bash? I have two approaches which accomplish the job, but they both seem a bit clunky.

I'll illustrate my approaches using a dumbed-down example of counting three words.

using a here doc:

wc -w <<EOS
one two three
EOS

using echo:

echo 'one two three' | wc -w

As I said, both of these seem a bit clunky. Is there a cleaner way to accomplish this?

2 Answers 2

6
wc -w <<<"one two three"

is a shorter way.

2
  • I sometimes prefer writing this the other way around, to make it obvious the input flows to the command, e.g <<< "one two three" wc -w
    – PhilR
    Nov 15, 2011 at 10:10
  • @Phil, whatever pleases your aesthetics ;-) I personally prefer first command and then whatever arguments it accepts whether via input or as a command line parameters. Exception is environment variables, but when I have a choice (e.g. make, configure scripts) I put those at the end too. Nov 15, 2011 at 10:15
4

I've seen the echo one used most often.

A third option, which might be Bash-only (I haven't checked) is the "here-string", <<<

wc -w <<<"Hello people of StackOverflow"

(you can find out more about those in the Here Strings section of the Bash manual)

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.