Skip to content
Advertisement

Combining input and output shell IO redirection (in a nonstandard order)

What would this shell command do?

./myprogram > /dev/null < myfile.c

And in general, how is this different from the other order of using < and >? When can it be used?

I ask because I can only find examples of the other order (./myprog < myinputs.txt > myoutputs.txt which straightforwardly takes in the contents of myinputs.txt and writes the result of running ./myprog on them into myoutputs.txt), and the only example I could find of something close to this resembled ./myprogram > myoutputs.txt << EOF, but that just appends EOF to myoutputs.txt after ./myprogram writes output to it.

Advertisement

Answer

This statement:

./myprogram >/dev/null <myfile.c

is identical to:

./myprogram <myfile.c >/dev/null

In this case, it matters not in which order the redirection is done.

More complex cases

The order of redirection does matter when the target of the redirection is itself being redefined. For example, consider:

cmd >/dev/null 2>&1

In the above, both stdout and stderr go to /dev/null. Now, consider:

cmd 2>&1 >/dev/null

In this case, by contrast, stderr is first redirected to stdout which, at the time of redirection and assuming no prior redirection, is the file handle associated with the terminal. Second, stdout is redirected to /dev/null. This has no effect on stderr because its output continues to go to the terminal.

In other words, 2>&1 does not assign stderr to stdout. Rather, it assigns stderr to the file handle currently associated with stdout. Subsequent redirection of stdout to another file handle makes no difference. That is why order matters here.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement