Pipes, redirection and small scripts

Unit 4 of 5 in Operating systems and the command line.

You will be able to chain commands, send output to files and write a small script that quotes its variables.

Lesson

Pipes: small tools, joined

A pipeline is a sequence of commands separated by the vertical bar. The output of each command is connected through a pipe to the input of the next, so each command reads what the previous one printed. A pipe itself is a one-way channel with a read end and a write end.

That is the core idea of the command line: many small tools that each do one job, joined into something larger. A defender uses it to take a huge log, keep the lines that matter, pull out one column and count the results.

Redirection: choosing where input and output go

Before a command runs, the shell can redirect where it reads from and writes to. Redirection can send output to a file, read input from a file, or point one stream at another. The shell sets it up before the command starts, so the command itself does not need to know.

One caution from the labs: redirecting output into an existing file with a single arrow replaces its contents without asking. Use the append form when you mean to add to a log.

Scripts: save what worked

A shell script is a text file of shell commands. Run it, and the shell reads and executes the commands in it. Anything you typed twice is a candidate for a script, and a script is also a written record of what you did.

Quote your variables

Quoting removes the special meaning of characters to the shell. It matters most with variables. After a variable is expanded outside double quotes, the shell splits the result into separate words wherever there is a space or other separator.

So a file named with a space can turn into two arguments, and a script that was meant to remove one file can touch two. Putting double quotes around variable expansions keeps the value as one word. This one habit prevents a large share of script accidents.

Key points

Sources

Practice in the labs

Build a few pipelines on a sample log, then write a script of your own.

Knowledge check

  1. What does a pipe connect? Answer: One command's output to the next command's input. The Bash manual says the output of each command in the pipeline is connected through a pipe to the input of the next.
  2. You run a command that redirects its output to an existing log with a single arrow. What happens to the old contents? Answer: They are replaced. A single-arrow redirection writes to the file from the start and replaces what was there. Use the append form to add to a file.
  3. Why quote a variable such as a filename in a script? Answer: Unquoted results are split into separate words at spaces. Word splitting (Bash manual) splits the results of expansions outside double quotes at separators, so a name with a space becomes two arguments unless quoted.

Back to the syllabus or see all classes.

Related