Redirecting Input and Output


Output

  • 2 types of outputs
    • Standard output is for normal program messages
    • Standard error contains error messages
      • represented by 2 at the CLI
  • separates errors from standard outputs so they don’t causes issues for programs that take as input outputs from other programs

Redirection Operators

Redirection OperatorEffect
>Creates a new file containing the standard output, or overwrites if exists.
>>Appends standard output to the existing file, or creates if not existent.
2>Creates a new file containing error messages (standard error), or overwrites if exists.
2>>Appends standard error to the existing file, or creates if doesn’t exist.
&>Creates a new file containing both standard output and standard error, or overwrites if exists.
<Sends the contents of the specified file to be used as standard input.
<<Accepts text on the following lines as standard input.
<>Causes the specified file to be used for both standard input and standard output.
  • can redirect standard errors to /dev/null to discard them
    • is a device that serves as a trash can

Pipes

A pipeline |, or pipe, redirects standard output from one program as standard input to a second program.

Generating Command Lines

xargs

The xargs command’s purpose in a pipeline is to build a command from its standard input.

  • syntax: xargs [OPTIONS] [COMMAND [INITITAL-ARGUMENTs]]
    • COMMAND is the command you want to execute
    • [OPTIONS] are xargs options; not passed to COMMAND
  • when you run it, it runs command once for every word passed to it on standard input, adding that word to the argument list for COMMAND
  • to pass multiple options to the command, protect them in enclosing quotes

Backticks

Backticks `` take text placed within them and treat it as a separate command whose results are substituted on the command line.

  • called command substitution

$() Format

  • using backtick is not commonly used to due to confusion with single quotes

$() is a command substitution format that executes the command placed within it first.