Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect output from file to stdout

I have a program that can output its results only to files, with -o option. This time I need to output it to console, i.e. stdout. Here is my first try:

myprog -o /dev/stdout input_file

But it says:

/dev/ not writable

I've found this question that's similar to mine, but /dev/stdout is obviously not going to work without some additional magic.

Q: How to redirect output from file to stdout?

P.S. Conventional methods without any specialized software are preferable.

like image 984
Mark Karpov Avatar asked Jun 16 '15 08:06

Mark Karpov


3 Answers

Many tools interpret a - as stdin/stdout depending on the context of its usage. Though, this is not part of the shell and therefore depends on the program used.

In your case the following could solve your problem:

myprog -o - input_file
like image 64
Rambo Ramon Avatar answered Sep 28 '22 01:09

Rambo Ramon


If the program can only write to a file, then you could use a named pipe:

pipename=/tmp/mypipe.$$
mkfifo "$pipename"

./myprog -o "$pipename" &

while read line
do
    echo "output from myprog: $line"
done < "$pipename"

rm "$pipename"

First we create the pipe, we put it into /tmp to keep it out of the way of backup programs. The $$ is our PID, and makes the name unique at runtime.

We run the program in background, and it should block trying to write to the pipe. Some programs use a technique called "memory mapping" in which case this will fail, because a pipe cannot be memory mapped (a good program would check for this).

Then we read the pipe in the script as we would any other file.

Finally we delete the pipe.

like image 38
cdarke Avatar answered Sep 28 '22 01:09

cdarke


You can cat the contents of the file written by myprog.

myprog -o tmpfile input_file && cat tmpfile

This would have the described effect -- allowing you to pipe the output of myprog to some subsequent command -- although it is a different approach than you had envisioned.

In the circumstance that the output of myprog (perhaps more aptly notmyprog) is too big to write to disk, this approach would not be good.

A solution that cleans up the temp file in the same line and still pipes the contents out at the end would be this

myprog -o tmpfile input_file && contents=`cat tmpfile` && rm tmpfile && echo "$contents"

Which stores the contents of the file in a variable so that it may be accessed after deleting the file. Note the quotes in the argument of the echo command. These are important to preserve newlines in the file contents.

like image 28
scottgwald Avatar answered Sep 28 '22 00:09

scottgwald