2

Is it possible to insert the result of a command (or even a chain of commands) into an executable in one command? Something like this:

./a.out < echo 0

Or is it necessary to do this:

echo 0 > input.txt
./a.out < input.txt
  • 2
    You mean a pipe? echo 0 | ./a.out – Ernest A Oct 27 '15 at 23:08
  • That works! How to do multiple commands though? echo 0 | cat test.txt | ./a.out only inserts test.txt. – Bart Louwers Oct 27 '15 at 23:22
  • 1
    Use compound commands { echo 0; cat test.txt; } | ./a.out -> gnu.org/software/bash/manual/html_node/Command-Grouping.html – chaos Oct 27 '15 at 23:24
  • @chaos: that is exactly what I was looking for. :-) I've updated your answer and accepted it in advance. – Bart Louwers Oct 27 '15 at 23:36
  • This should be refered as feeding the output of a command into another as input… – Mingye Wang Oct 28 '15 at 1:59
3

When you want the program a.out to read the output of the command echo 0 as its input, then you can do that like this:

echo 0 | ./a.out

Or (this is bash specific):

./a.out < <(echo 0)

This > and this < instead are redirection operators, > is the redirection of the output and < of the input.

This:

echo 0 > input.txt

Redirects the output of echo to a file called input.txt


This:

./a.out < input.txt

Redirects the input of ./a.out; the source are the contents of input.txt.


For multiple commands, use compound commands:

{ echo 0; cat test.txt; } | ./a.out
| improve this answer | |
  • Thank you! I already tried ./a.out <(echo 0) but my shell wouldn't accept it! (-bash: syntax error near unexpected token ( ) – Bart Louwers Oct 27 '15 at 23:14
  • @ultrabowser Sorry, my fault it's ./a.out < <(echo 0), it's late... – chaos Oct 27 '15 at 23:21
0

Just to note that there is a simpler code (in bash):

./a.out <<<"0"

Or even:

 <<<"0" ./a.out

If you do not mind the "reverse looking" writing.

| improve this answer | |

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