Lably
Skip to content

Redirection (computing)

  • 7 min read
  • 5 chapters

Related on Lably

Through Computing, Unix shell and Input/output

In Unix-like operating systems, programs do redirection with the dup2(2) system call, or its less-flexible but higher-level stdio analogues, freopen(3) and popen(3).

Redirecting standard input and standard output

Redirection is usually implemented by placing certain characters between commands.

Basic

Typically, the syntax of these characters is as follows, using < to redirect input, and > to redirect output. command > file1 executes command, placing the output in file1, as opposed to displaying it at the terminal, which is the usual destination for standard output. This will clobber any existing data in file1.

Using command < file1 executes command, with file1 as the source of input, as opposed to the keyboard, which is the usual source for standard input.

command < infile > outfile combines the two capabilities: command reads from infile and writes to outfile

Variants

To append output to the end of the file, rather than clobbering it, the >> operator is used: command1 >> file1.

To read from a stream literal (an inline file, passed to the standard input), one can use a here document, using the << operator:

<span id="mwZg"></span><span class="gp" id="mwZw">$ </span>tr<span class="w" id="mwaA"> </span>a-z<span class="w" id="mwaQ"> </span>A-Z<span class="w" id="mwag"> </span><span class="s" id="mwaw"><< END_TE</span>XT <span class="go" id="mwbA">> one two three</span> <span class="go" id="mwbQ">> uno dos tres</span> <span class="go" id="mwbg">> END_TEXT</span> <span class="go" id="mwbw">ONE TWO THREE</span> <span class="go" id="mwcA">UNO DOS TRES</span>

To read from a string, one can use a here string, using the <<< operator: tr a-z A-Z <<< "one two three", or:

<span id="mwgA"></span><span class="gp" id="mwgQ">$ </span><span class="nv" id="mwgg">NUMBERS</span><span class="o" id="mwgw">=</span><span class="s2" id="mwhA">"one two three"</span> <span class="gp" id="mwhQ">$ </span>tr<span class="w" id="mwhg"> </span>a-z<span class="w" id="mwhw"> </span>A-Z<span class="w" id="mwiA"> </span><span class="o" id="mwiQ"><<<</span><span class="w" id="mwig"> </span><span class="s2" id="mwiw">"</span><span class="nv" id="mwjA">$NUMBERS</span><span class="s2" id="mwjQ">"</span> <span class="go" id="mwjg">ONE TWO THREE</span>

Sign in to keep reading

4 more chapters are free with a Lably account.

More in Computing and communication