Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: read stdin from file and write stdout to file

Tags:

linux

bash

I'm trying to run an app (let's say top) so it will read from a file for stdin and write to another file from stdout.

Currently I have

mkfifo stdin.pipe
(tail -f stdin.pipe) | top

which works as expected, as I can then echo something to that file and top will receive it. But I'm unable to redirect the output of top. How can I achieve this?

EDIT:

Ok, let's scratch top. I'm testing with this:

cat test.sh

echo Say something
read something
echo you said $something
like image 571
alexandernst Avatar asked Mar 28 '13 11:03

alexandernst


2 Answers

Let's forget about top, that appears to be a red herring.

To map stdin or stdout to files, you can use redirection:

some_program < input_file          # Redirects stdin

another_program > output_file      # Redirects stdout

or even:

yet_another  < input_file > output_file
like image 62
cdarke Avatar answered Nov 07 '22 00:11

cdarke


Is there a way I can map stdin and stdout to files and use them to control a cli app?

It sounds like you are looking for coprocesses, added to Bash in 4.0.

coproc cat                    # Start cat in background
echo Hello >&${COPROC[1]}     # Say "Hello" to cat
read LINE <&${COPROC[0]}      # Read response
echo $LINE                    # cat replied "Hello"!

Before 4.0 you had to use two named pipes to achieve this.

like image 37
Joni Avatar answered Nov 07 '22 00:11

Joni