Input and Output Redirection

How can I get my program to take input from a file rather than me typing it in? How can I get it to send output to a file rather than the screen?


Redirecting input and output

To tell a program myprog, which lives in the current directory, to get its input from a file input.txt, use


torbernite% ./myprog < input.txt

To send normal output (e.g, the results of print statements) to output.txt, use


torbernite% ./myprog > output.txt

Note though that this will overwrite anything already in output.txt - to append the data to the file instead, use


torbernite% ./myprog >> output.txt

Many programs have error output (STDERR, or standard error) as well as normal output (STDOUT, or standard output). The syntax for sending standard error to a file is, unfortunately, different in different shells. Most people in the Institute will be using the tcsh shell, but you may be using bash instead - to find out, use the echo $SHELL command (note that if you have manually started a different shell from your default, this will give the wrong answer - but in this case you will know what shell you started anyway).

In tcsh: to send standard output to output.txt and standard error to errors.txt, type


torbernite% (./myprog > output.txt) >& errors.txt

(note that the brackets are important). To send both standard output and standard error to alloutput.txt, use


torbernite% ./myprog >& alloutput.txt

In bash, the equivalent commands are

torbernite$ (./myprog > output.txt) 2> errors.txt 

and


torbernite$ ./myprog > alloutput.txt 2>&1

You can, of course, combine the redirections above with each other, where appropriate. For example, the following line (using tcsh) runs myprog, sending it input from input.txt and putting its standard output in output.txt and its standard error in errors.txt:


torbernite% (./myprog > output.txt) < input.txt >& errors.txt


Other relevant help topics

Input and output redirection is very useful in combination with running a job in the background.

Please contact us with feedback and comments about this page. Last updated on 25 Mar 2022 15:43.