Redirections and pipes

The three standard streams, the redirections >, >>, <, 2> and 2>&1, /dev/null, the pipe and tee, and the order in which the shell applies them.

  • 23 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand

A few cards from the deck

  • Standard streams: what is it?

    Show the answer

    The three channels every process has open from the start: standard input, standard output and standard error.

    By default, input is the keyboard, output and error are the screen. Keeping the two outputs apart lets you redirect results without losing error messages.

  • With ls /etc/passwd /nope > out, what is on the screen and what is in out?

    • Screen: the /nope error; out: /etc/passwd
    • The screen stays empty; out contains /etc/passwd and the error
    • The screen shows /etc/passwd; out contains the error about /nope
    • The screen shows both lines; out is created but stays empty
    Show the answer

    Screen: the /nope error; out: /etc/passwd

    > only redirects standard output (descriptor 1). The message “ls: cannot access '/nope': No such file or directory” goes to the error output, so to the screen.

  • Standard input has the number …, standard output … and standard error ….

    Show the answer

    Standard input has the number 0, standard output 1 and standard error 2.

    A bare > is a shortcut for 1>. That is why 2> is needed to catch errors.

  • > and >>: what is it?

    Show the answer

    Send standard output into a file: the first overwrites it, the second appends to the end.

    Both create the file if it does not exist. > empties it as soon as the shell opens it, before the command even runs.

  • After sort notes.txt > notes.txt, the file notes.txt is empty. Which command really sorts the file?

    • sort -o notes.txt notes.txt
    • sort notes.txt >> notes.txt
    • sort notes.txt | notes.txt
    • sort < notes.txt > notes.txt
    Show the answer

    sort -o notes.txt notes.txt

    The shell opens notes.txt for writing, thus empties it, before sort reads it. -o lets sort read the whole file before writing. >> would append the sorted lines, | would look for a command notes.txt, and the < version empties the file the same way. You can also go through a temporary file then mv.