LINUX · LPI LINUX ESSENTIALS · CHAPTER 4

The Power of the Command Line

Archive, search, chain commands and automate with scripts.

6 min readDomain 013 · Data ProcessingLevel: beginner

From point A to point B

Point A: you already move around the system and handle files, but you do every task by hand, one at a time. Point B: by the end of this chapter you will package and compress folders, search and extract information from huge files, chain commands with pipes and turn repetitive tasks into scripts.

Together with the previous one, this is the most heavily weighted block of the exam, and your first step toward automation: what you do today in ten commands, a script will do for you tomorrow.

Archiving and compressing

These are two different actions. Archiving gathers many files and folders into a single one; compressing reduces its size. tar archives, and with one option it also compresses.

tar -cf backup.tar project/          # c: create · f: archive file name
tar -tf backup.tar                    # t: list the contents without extracting
tar -xf backup.tar                    # x: extract into the current directory
tar -xf backup.tar -C /tmp/restore  # extract into another directory

tar -czf backup.tar.gz project/      # z: compress with gzip
tar -cjf backup.tar.bz2 project/     # j: compress with bzip2
tar -cJf backup.tar.xz project/      # J: compress with xz
tar -xzvf backup.tar.gz               # v: shows each file (verbose)
ToolCompressDecompressExtension
gzipgzip filegunzip file.gz.gz
bzip2bzip2 filebunzip2 file.bz2.bz2
xzxz fileunxz file.xz.xz
zipzip -r backup.zip folder/unzip backup.zip.zip

In general, xz compresses more but is slower; gzip is the fastest. gzip, bzip2 and xz replace the original file; add -k if you want to keep it. zip archives and compresses at the same time and is the format most compatible with Windows.

Absolute paths in tar. For safety, GNU tar strips the leading slash when archiving /etc, so on extraction it creates etc/ wherever you are. The -P option keeps the absolute path and, on extraction, overwrites the original system files. Use it only if you know exactly what you are restoring.
du -sh project/ backup.tar.gz     # compares sizes before and after

Viewing text: cat, less, head and tail

cat notes.txt              # shows the whole file
cat -n notes.txt           # with line numbers
less /var/log/syslog       # paged: space moves forward, / searches, q quits
head /var/log/syslog       # the first 10 lines
head -n 30 /var/log/syslog # the first 30
tail -n 20 /var/log/syslog # the last 20
tail -f /var/log/syslog    # follows the file live: ideal for logs

less is the evolution of more: it does not load the whole file into memory, so it opens files with millions of lines instantly. With head and tail on several files, -q hides each file name.

Counting, cutting and sorting

wc /etc/passwd             # lines, words and bytes
wc -l /etc/passwd          # lines only: how many users there are

cut -d ":" -f1 /etc/passwd       # field 1 with ":" as the separator: user names
cut -d ":" -f1,7 /etc/passwd     # user and shell
cut -c1-10 /etc/passwd           # characters 1 to 10 of each line

sort names.txt           # alphabetical order
sort -r names.txt        # reverse
sort -n numbers.txt        # numeric: 2 before 10
uniq -c names.txt        # counts consecutive repetitions
Sort before you use uniq. uniq only removes or counts consecutive repeated lines. That is why it almost always comes after sort: sort names.txt | uniq -c.

Redirection and pipes

Every command has three channels: standard input (0), standard output (1) and standard error (2). You can redirect them to files or connect them between commands.

Standard streams, redirection and pipes Every command has three streams: standard input 0, standard output 1 and standard error 2. A pipe sends the output of grep into sort and then into uniq -c. The final output is redirected to a file with greater-than, and errors are sent to /dev/null with 2 greater-than. STDIN 0 · STDOUT 1 · STDERR 2 access.log< stdin grep 404 sort uniq -c report.txt> stdout || 2> /dev/null stderr: errors go elsewhere grep 404 < access.log 2>/dev/null | sort | uniq -c > report.txt

A pipe passes the output of one command to the input of the next. Diagram: The House of Routing.

OperatorWhat it does
>Sends the output to a file and overwrites it
>>Appends the output to the end of the file
2> / 2>>The same, but with errors
&> / &>>Output and errors together
<Uses a file as input
|Pipe: the output of one command is the input of the next
echo "hello world" > greeting.txt
echo "second line" >> greeting.txt
du -sh /* 2> /dev/null              # discards permission errors
cp -r source/ destination/ &>> backup.log
mysql shop < backup.sql            # restores a database from a file

cut -d ":" -f7 /etc/passwd | sort | uniq -c   # how many users use each shell

/dev/null is a special device that discards everything it receives: the system's "black hole".

Searching with grep and regular expressions

grep shows the lines that contain a pattern.

grep jesus /etc/passwd          # lines that contain "jesus"
grep -i error app.log           # case-insensitive
grep -v nologin /etc/passwd     # lines that do NOT contain the pattern
grep -n root /etc/passwd        # with line numbers
grep -c bash /etc/passwd        # how many lines match
grep -w 100 data.txt           # only the exact word "100"
grep -r "Listen" /etc/apache2/  # recursive in a directory

Regular expressions

A regular expression describes a pattern. By default, grep looks for the match anywhere in the line; the anchors ^ and $ pin it to the start or the end.

SymbolMeaningExample
.Any characterr..t → root, rest
^ / $Start / end of line^root, bash$
[ ] / [^ ]One from the list / none from the list^[jJ], [^0-9]
*The previous item, zero or more timesab*c → ac, abc, abbc
+ / ?One or more / zero or one time (extended)[0-9]+
{n,m}Between n and m repetitions (extended)[a-z]{3,6}
a|bOne or the other (extended)error|fail
[[:alpha:]]Classes: letters, digits (digit), whitespace (space)…[[:digit:]]{4}

With grep -E (extended regular expressions) you can use +, ?, { } and | without escaping them. Version 2.0 of the exam works with extended expressions.

grep '^j' /etc/passwd                          # users that start with j
grep -E '^[h-z]{8}$' /usr/share/dict/words     # words of exactly 8 letters between h and z
grep -E 'error|fail' app.log                   # one or the other
grep -E '^[jar]' /etc/passwd | cut -d ":" -f1 > users.txt

Text editors: nano and vi

nano is the simplest. Shortcuts appear at the bottom; the ^ symbol means Ctrl: ^O saves, ^X exits, ^W searches.

vi (and its improved version, vim) is on practically every Unix system, including the most minimal server. It works with modes:

ModeWhat forKey keys
Normal (command)Move around and edit with shortcutsdd deletes the line · yy copies · p pastes · u undoes
InsertType texti enters · Esc returns to normal mode
Command line (ex)Save, quit, search and replace:w saves · :q quits · :wq both · :q! quits without saving

There is also emacs, with a graphical or terminal mode (emacs -nw). The exam only asks you to know nano and vi.

Your first scripts

A script is a text file with commands that the shell runs in order. It lets you automate repetitive tasks.

#!/bin/bash
# info.sh · shows data about the run
echo "Script: $0"
echo "User: $USER"
echo "PID: $$"
echo "First argument: $1"
echo "Number of arguments: $#"
echo "All arguments: $@"
chmod +x info.sh
./info.sh hello world

Reading input and doing math

#!/bin/bash
read -p "First number: " n1
read -p "Second number: " n2
echo "Sum: $((n1 + n2))"
echo "Product: $((n1 * n2))"
echo "Integer division: $((n1 / n2)) · remainder: $((n1 % n2))"

Conditions with test and if

test and its short form [ ] check a condition. Always leave a space after [ and before ].

TypeOperators
Numbers-eq equal · -ne not equal · -gt greater · -ge greater or equal · -lt less · -le less or equal
Text= equal · != not equal · -z empty · -n not empty
Files-e exists · -f is a file · -d is a directory · -r/-w/-x permissions
#!/bin/bash
read -p "Grade (0-10): " grade
if [ "$grade" -ge 9 ]; then
  echo "Excellent"
elif [ "$grade" -ge 7 ]; then
  echo "Very good"
elif [ "$grade" -ge 5 ]; then
  echo "Pass"
else
  echo "Fail"
fi
#!/bin/bash
read -p "Path: " path
if [ ! -e "$path" ]; then
  echo "The path does not exist"
  exit 1
elif [ -d "$path" ]; then
  echo "It is a directory"
else
  echo "It is a file"
fi

Put variables in double quotes inside [ ]: if they are empty or contain spaces, the script does not break.

Loops: for and while

#!/bin/bash
for server in web01 web02 db01; do
  echo "Checking $server"
done

for n in $(seq 1 5); do echo "Round $n"; done

count=0
while [ $count -lt 5 ]; do
  echo "Counter: $count"
  count=$((count + 1))
done

Exit code

Every command ends with a code: 0 if everything went well and another number if it failed. You check it with $? and set it in your scripts with exit.

grep -q root /etc/passwd
echo $?         # 0: it found it
ls /does-not-exist
echo $?         # 2: error

Linux Essentials-style challenge

Answer before you open the solution. Getting it wrong here is the cheapest way to learn.

1. What does tar -czf backup.tar.gz docs/ do?

It creates a gzip-compressed tar archive named backup.tar.gz with all the contents of docs/.

2. You want to save a command's errors to errors.log without erasing what it already contained. Which operator do you use?

2>>: the 2 refers to standard error and >> appends to the end instead of overwriting.

3. Why does uniq -c names.txt show the same name several times?

Because uniq only groups consecutive lines. Sort first: sort names.txt | uniq -c.

4. A script starts with #!/bin/bash. What does that line indicate?

The interpreter that should run it (the shebang). That way it runs with Bash even if you launch it from another shell.

What you take away

  • tar archives; z, j and J compress with gzip, bzip2 and xz.
  • less to read, tail -f to follow logs live.
  • cut, sort, uniq and wc turn text into information; uniq always after sort.
  • > overwrites, >> appends, 2> is for errors and | chains commands.
  • grep -E with ^, $, [ ] and {n,m} finds almost any pattern.
  • A script: shebang, chmod +x, arguments $1 and $#, if, for, while and exit.

In the next chapter you look inside the system: hardware, processes, boot, logs and networking.

Official resources

Source and credits. Chapter written from Jesús Espinoza's study notes for the LPI Linux Essentials certification (2022), updated to version 2.0 of the exam (010-200). Text drafted with AI assistance; original diagrams by The House of Routing. Technical details were checked against the official documentation from LPI, GNU and the distributions.

Navigate