Alana Storm
Alana Storm

Reputation: 166076

Tricking a Unix Commandline Program into Accepting a File Stream

Hypothetical situation. I have a command line program in *nix (linux, BSD, etc.). It was written so that you pass it a text file as an argument

$ program file.txt

Run the program, it looks at the text in file.txt.

Is it possible to "trick" this program into accepting input from a file stream rather than reading a file via disk? I'm pretty comfortable using unix pipes to do stuff, but there's still something a little mysterious about their internals that make it so I can't say (definitively) yes or not to the above question.

Upvotes: 2

Views: 662

Answers (4)

wnoise
wnoise

Reputation: 9932

In addition to the shell-managed trickery of the other answers:

Some unix systems have the special files /dev/stdin, and you can run e.g.

otherprogram | program /dev/stdin

Others (e.g. linux) may have /proc/self/fd/0 which may be used the same way.

Both of these will fail if stdin is closed before the file on the command line is opened, but this will be an extremely rare occurrence. Much more likely will be it failing because the program expects to seek() the file, which does not work on pipes.

If your shell is zsh, you have another option.

program =(otherprogram)

Which will do all the bother of setting up a temporary input file and removing it after program terminates. This will work with seek(), but may temporarily take more space.

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342433

if your program is not coded to accept standard input, it won't work even if you use named pipes or process substitution

Upvotes: 1

mouviciel
mouviciel

Reputation: 67839

You may be interested in named pipes:

mkfifo myPipe
program myPipe &
anotherProgram > myPipe

is equivalent to:

anotherProgram | program

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798716

bash lets you do this:

program <(otherprogram)

This uses the output of otherprogram as the contents of a file passed to program.

Upvotes: 4

Related Questions