Reputation: 1862
If I have a C++ program that expects input to cin from the console during run-time, how can I automate this input from a shell script? I also need to store its output in a file but that part is easy. I have researched different ways including echo-ing it to the file descriptor of the pid in /proc, but nothing seems to work.
Here is what I have so far:
#!/bin/sh
g++ -o runme source.cpp
echo <<EOT | ./runme > output
expected program input
more expected program input
even more
EOT
Note that each line of input requires an "enter key-press" to be read by cin in the program, which I am assuming should happen since the program input in the script is separated by new-lines. Here, the program gets executed but the same output is produced in the file regardless of what I put before the EOT so it's not being entered to cin of the program as expected.
Upvotes: 0
Views: 3101
Reputation: 532538
Just FYI, echo
does not read from its standard input (which a here document provides); you would want to use cat
instead:
cat <<EOF | ./runme > output
...
...
...
EOF
But this is a useless use of cat
, since you can just connect the here document to runme
's standard input directly as shown by Thomas Nyman's answer.
Upvotes: 1
Reputation: 213
The form of I/O redirection you want is called a here document and does not involve echo
at all:
./runme <<EOF
expected program input
more expected program input
even more
EOF
With output redirection:
./runme <<EOF > output
expected program input
more expected program input
even more
EOF
If you insist on using echo
, in principle you could do:
echo -e "expected program input\nmoreexpected program input\neven more\n" | ./runme
where the -e
option enables the interpretation of backslash escapes, such as the newlines indicated by \n
in the argument of echo
.
Upvotes: 5