Redirection

As mentioned above, there are always three default files open, stdin (the keyboard), stdout (the screen) and stderr (error messages output to the screen).

 

These, and any other open files, can be redirected.

 

The redirection operators are:

 

  • command > filename
    • Create file, if it doesn't already exist, and send output to it
    • If file does exist, its contents will be truncated (overwritten)
  • command >> filename
    • Append output to file
    • Create file, if it doesn't already exist
  • command < filename
    • Read input from file

 

Redirection simply means capturing output from a file, command, program, script, or even code block within a script and sending it as input to another file, command, program, or script.

 

Send output from previous shell script into text file:

#! /bin/bash

arrayIntersections.sh > foundIPs.txt

 

Append output from previous shell script to text file

#! /bin/bash

arrayIntersections.sh >> foundIPs.txt

 

Read text file into cat command:

#! /bin/bash

cat < ~/foundIPs.txt

 

Similarly, redirection can be performed on:

  1. stdout to a file
  2. stderr to a file
  3. stdout to a stderr
  4. stderr to a stdout
  5. stderr and stdout to a file
  6. stderr and stdout to stdout
  7. stderr and stdout to stderr

 

#!/bin/bash

#write stdout to file
ls -l > myfiles.txt

#write stderr to file
ls*mv 2> errors.txt

#write stdout to stderr
ls -la 1>&2

#write stderr to stdout
ls*mv 2>&1

#write stdout and stderr to file
ls*mv &> outErr1.txt
#or...
ls*mv >^ outErr2.txt

echo "Redirect this STDOUT to STDERR" 1>&2

 

 

The redirector operators can also be combined:

#! /bin/bash

cat < ~/foundIPs.txt > copy.txt