Level 3

Advanced: Understanding and controlling your system

Here you'll learn how Linux works underneath: who's allowed to do what, what's running, how disks and networks are managed, and how to automate tasks and fix problems yourself.

Before you start

This level assumes you're comfortable with everything in Level 2, especially moving around in the terminal and using sudo. Commands are shown for Ubuntu/Mint. Most work the same everywhere; differences are noted.

3.1 The folder tree explained

In Level 1 you learned that everything starts at /. Here's what the main folders are for. Most distros follow this same layout.

FolderWhat's in itRough Windows equivalent
/homeEach user's personal folderC:\Users
/rootThe administrator's home folderβ€”
/etcSystem-wide settings, as plain text filesThe Registry (but readable!)
/usrInstalled programs and their filesC:\Program Files
/usr/binThe programs themselves (commands like ls)β€”
/varData that changes: logs (/var/log), caches, databasesC:\ProgramData
/tmpTemporary files, emptied on restart%TEMP%
/bootFiles needed to start the computer, including the kernelβ€”
/devHardware devices, shown as files (e.g. /dev/sda = first disk)Device Manager
/media, /mntWhere USB sticks and other drives appearD:, E:…
/proc, /sysLive information about the system, generated by the kernelβ€”
"Everything is a file"

A central Linux idea is that almost everything appears as a file: documents, but also disks, hardware and even running programs. Try cat /proc/cpuinfo to "read" your processor, or cat /proc/meminfo for memory. The same simple tools work on everything.

Your personal settings live in hidden folders in your home: mostly ~/.config, with some data in ~/.local/share. If an app behaves strangely, renaming its folder in ~/.config resets it to default settings.

3.2 Users, groups and permissions

Linux was designed from the start for many people sharing one computer. Every file has an owner, belongs to a group, and has permissions saying who may do what with it.

Reading permissions

$ ls -l
-rw-r--r-- 1 anna anna  2048 Nov 26 10:00 notes.txt
drwxr-xr-x 2 anna anna  4096 Nov 26 10:05 Photos
-rwxr-xr-x 1 anna anna   512 Nov 26 10:10 backup.sh

The first column is the key. Take -rwxr-xr-x:

-rwxr-xr-x
Type: - file, d folder, l linkOwner (anna)Group (anna)Everyone else

So backup.sh above can be read, changed and run by anna, and read and run (but not changed) by everyone else.

Changing permissions: chmod

$ chmod +x backup.sh        # make it runnable
$ chmod go-r diary.txt     # remove read for group (g) and others (o)
$ chmod u+w notes.txt      # give the owner (u = user) write access

You'll also see permissions as numbers: read = 4, write = 2, execute = 1, added together for owner, group and others:

$ chmod 644 notes.txt       # rw-r--r--  (6=4+2, 4, 4) typical for files
$ chmod 755 backup.sh       # rwxr-xr-x  (7=4+2+1, 5=4+1, 5) typical for programs
$ chmod 600 secret.txt      # rw-------  only me

Changing the owner: chown

$ sudo chown anna file.txt          # make anna the owner
$ sudo chown -R anna:anna /mnt/data # owner and group, for a folder and everything inside

Users and groups

$ id                         # who am I, and which groups am I in?
$ sudo adduser ben           # create a new user (Debian/Ubuntu/Mint)
$ sudo useradd -m ben        # same, on other distros (then: sudo passwd ben)
$ sudo usermod -aG docker anna   # add anna to the "docker" group (log out and in to apply)

Groups grant shared access. Being in the sudo group (called wheel on Fedora and Arch) is what allows you to use sudo.

Careful

Never "fix" a permission problem with chmod -R 777. It gives everyone full control, which is a security hole and can break programs that check permissions (like SSH). Find out who needs access and give only that.

3.3 Pipes, redirection and searching

The real power of the terminal comes from combining small commands, each doing one job well.

Pipes: |

A pipe sends the output of one command into the next one, like an assembly line.

$ ls -l /usr/bin | less                # page through a long list
$ history | grep apt                   # find past commands containing "apt"
$ du -sh ~/* | sort -h                 # sizes of your folders, smallest to largest
$ cat names.txt | sort | uniq | wc -l  # count unique lines

Redirection: > and >>

$ ls ~/Music > music-list.txt     # save output to a file (overwrites!)
$ date >> log.txt                  # add to the end of a file
$ somecommand 2> errors.txt       # save only error messages
$ somecommand > /dev/null 2>&1    # throw away all output

Finding files: find

$ find ~ -name "*.pdf"                  # all PDFs in your home
$ find ~ -iname "*holiday*"             # name contains "holiday", any case
$ find ~/Downloads -size +500M          # files bigger than 500 MB
$ find ~/Downloads -mtime +90           # not changed in 90 days

Searching inside files: grep

$ grep "password" notes.txt             # lines containing "password"
$ grep -i "error" /var/log/syslog       # ignore upper/lower case
$ grep -rn "TODO" ~/Projects            # search all files in a folder, show line numbers
Try it

Find your 10 largest files in Downloads:

$ find ~/Downloads -type f -exec du -h {} + | sort -h | tail -n 10

Read it part by part: find files β†’ measure each one β†’ sort by size β†’ show the last 10.

3.4 Processes: what's running

Every running program is a process with an ID number called a PID. The graphical tool is System Monitor (like Task Manager). In the terminal:

$ top                      # live view of processes (q to quit)
$ htop                     # a nicer, colourful version (install "htop")
$ ps aux                   # snapshot of every process
$ ps aux | grep firefox    # find a specific one
$ pgrep -l firefox         # shorter way to get its PID

Stopping a frozen program

$ kill 4321               # politely ask process 4321 to close
$ kill -9 4321            # force it (unsaved work is lost)
$ pkill firefox           # close by name
$ xkill                   # then click a frozen window to close it (X11 desktops only)

Running things in the background

$ long-task &            # start it in the background, keep using the terminal
$ jobs                    # list background jobs
$ fg                      # bring the last one back to the front

Press Ctrl+Z to pause a running command, then bg to continue it in the background.

Memory and load

$ free -h                 # memory use
$ uptime                  # how long it's been on + "load average"
Why is my memory "full"?

Linux uses spare memory as a cache to speed things up and gives it back instantly when a program needs it. Look at the "available" column in free -h, not "free". Unused memory is wasted memory.

3.5 Services and logs

Services (also called daemons) are programs that run in the background: networking, printing, Bluetooth, the login screen and so on. On almost all modern distros they're managed by systemd with the systemctl command.

$ systemctl status cups              # is the printing service running?
$ sudo systemctl restart cups        # restart it
$ sudo systemctl stop bluetooth      # stop now
$ sudo systemctl start bluetooth     # start now
$ sudo systemctl enable --now sshd   # start now AND at every boot
$ sudo systemctl disable bluetooth   # don't start at boot
$ systemctl --failed                 # anything that failed to start?
Coming from Windows

systemctl is the equivalent of the Services app (services.msc). "Enable" is the same as setting a service to Automatic startup.

Reading logs: journalctl

When something goes wrong, the answer is usually in the logs. Most are collected by systemd's journal.

$ journalctl -b                   # everything since this boot
$ journalctl -b -p err            # only errors since this boot
$ journalctl -b -1 -p err         # errors from the PREVIOUS boot (great after a crash)
$ journalctl -u NetworkManager    # logs for one service
$ journalctl -f                   # follow new messages live (Ctrl+C to stop)
$ sudo dmesg                      # messages from the kernel (hardware, drivers)
Try it

Run sudo dmesg -w, then plug in a USB stick. Watch the kernel detect it in real time. Ctrl+C to stop.

3.6 Disks and storage

For most tasks the graphical Disks app (or GParted) is the easiest and safest way to manage drives. The terminal tools are good for seeing what's going on:

$ lsblk -f                  # all disks and partitions, with file system and labels
$ df -h                     # how full each mounted drive is
$ du -sh ~/Videos           # size of one folder
$ ncdu ~                    # interactive "what's using my space?" (install "ncdu")

Disk names

Mounting

Mounting means attaching a drive to a folder in the tree so you can use it. The desktop does this automatically for USB sticks. By hand:

$ sudo mkdir -p /mnt/data
$ sudo mount /dev/sdb1 /mnt/data
$ sudo umount /mnt/data            # note: "umount", not "unmount"

Mounting a drive automatically at startup: /etc/fstab

To have a second internal drive always available, add a line to /etc/fstab. First find its UUID (a unique ID that doesn't change, unlike sdb, which can):

$ lsblk -f
NAME   FSTYPE LABEL UUID                                 MOUNTPOINTS
sdb
└─sdb1 ext4   Data  3e6be9de-8139-11d1-9106-a43f08d823a6

$ sudo nano /etc/fstab
# add this line at the bottom:
UUID=3e6be9de-8139-11d1-9106-a43f08d823a6  /mnt/data  ext4  defaults,nofail  0  2

$ sudo systemctl daemon-reload
$ sudo mount -a          # test it: no output means success
Careful

A mistake in /etc/fstab can stop the computer from booting. Always run sudo mount -a to test before restarting. The nofail option makes the system boot even if the drive is missing. Commands like dd, mkfs and fdisk can wipe a whole disk in a second, so always double-check the device name with lsblk first.

Common file systems

3.7 Networking and firewall

$ ip a                      # your network interfaces and IP addresses
$ ip route                  # your router ("default via ...")
$ ping -c 4 9.9.9.9         # can I reach the internet? (by number)
$ ping -c 4 example.com     # can I reach it by name? (tests DNS)
$ nmcli device wifi list    # nearby Wi-Fi networks
$ nmcli device wifi connect "MyWiFi" --ask
$ ss -tulpn                 # which programs are listening for connections
A quick internet diagnosis

If ping 9.9.9.9 works but ping example.com doesn't, your connection is fine and the problem is DNS (the internet's "phone book" that turns names into numbers). If neither works, check the cable, Wi-Fi and router.

The firewall

A firewall controls which connections are allowed into your computer. Ubuntu and Mint use ufw ("uncomplicated firewall"). There's also a graphical version called Firewall Configuration (gufw).

$ sudo ufw enable            # turn on: blocks incoming, allows outgoing
$ sudo ufw status verbose
$ sudo ufw allow ssh         # allow incoming SSH (port 22)
$ sudo ufw delete allow ssh

Fedora uses firewalld instead (firewall-cmd, or the "Firewall" app), and it's on by default.

3.8 SSH: controlling other computers

SSH (Secure Shell) lets you open a terminal on another computer, like a Raspberry Pi, a home server or a web server, over an encrypted connection.

$ ssh anna@192.168.1.50            # log in to another machine
$ exit                             # come back

To allow others to SSH into your computer, install and start the server: sudo apt install openssh-server. (On Ubuntu/Mint the service is called ssh. On most other distros it's sshd, which you start with sudo systemctl enable --now sshd.)

Log in with keys instead of passwords

Keys are both safer and more convenient than passwords. You create a pair: a private key (stays on your computer, never share it) and a public key (copied to the computers you want to access).

$ ssh-keygen -t ed25519                    # create a key pair (press Enter for defaults, set a passphrase)
$ ssh-copy-id anna@192.168.1.50            # copy your public key to the other machine
$ ssh anna@192.168.1.50                    # now logs in with your key

Copying files between computers

$ scp photo.jpg anna@192.168.1.50:~/Pictures/          # copy one file
$ rsync -avh --progress ~/Music/ anna@192.168.1.50:~/Music/   # sync a folder (only copies changes)
Tip: the trailing slash in rsync

rsync ~/Music/ dest/ copies the contents of Music. rsync ~/Music dest/ copies the Music folder itself, creating dest/Music. Small slash, different result.

3.9 Customising your shell

Your shell (usually Bash) reads the file ~/.bashrc every time you open a terminal. Put your personal shortcuts there.

Aliases: your own short commands

# add to the end of ~/.bashrc
alias update='sudo apt update && sudo apt upgrade'
alias ll='ls -lah'
alias ..='cd ..'
alias myip='curl -s https://ifconfig.me; echo'

Then run source ~/.bashrc (or open a new terminal) to apply. Now typing update updates your whole system.

What does && mean?

a && b means "run a, and if it succeeded, run b". a ; b runs both regardless. a || b runs b only if a failed.

Environment variables and PATH

Variables are named values that programs can read. Some useful ones:

$ echo $HOME       # /home/anna
$ echo $USER       # anna
$ echo $PATH       # folders searched for commands, separated by ":"

When you type ls, the shell looks for a program called ls in each folder listed in PATH. To run your own scripts from anywhere, put them in ~/.local/bin, which most distros already include in PATH. If yours doesn't, add this line to ~/.bashrc:

export PATH="$HOME/.local/bin:$PATH"

which ls shows you which program a command actually runs.

3.10 Zsh and Oh My Zsh

Zsh (the "Z shell") is an alternative to Bash. It understands almost all the same commands, but adds smarter tab completion, better history and lots of comfort features. It's the default shell on macOS and a favourite on Linux. Oh My Zsh is a popular add-on that makes Zsh easy to customise with themes and plugins.

In plain words

If Bash is a reliable standard car, Zsh is the same car with a better dashboard. Oh My Zsh is a box of ready-made extras for it: themes for how it looks, and plugins for new tricks. You still drive it exactly the same way.

What you gain (Zsh + Oh My Zsh)

What doesn't change

Your scripts keep working. A script that starts with #!/bin/bash is still run by Bash, whatever shell you type in. Only your interactive terminal changes.

Step 1: Install Zsh and make it your shell

$ sudo apt install zsh git curl        # Ubuntu / Mint
$ sudo dnf install zsh git curl        # Fedora
$ sudo pacman -S zsh git curl          # Arch
$ zsh --version                        # check it's installed
$ chsh -s $(which zsh)                 # make it your default shell

Log out and back in for the change to take effect. Then echo $SHELL should show /usr/bin/zsh or /bin/zsh.

The first time Zsh starts without a config file, it shows a setup menu. You can press 0 to skip it, because Oh My Zsh creates the config for you in the next step.

Step 2: Install Oh My Zsh

The official one-line install from ohmyz.sh downloads a script and runs it immediately. It's a trustworthy project, but it's a good habit to download the script first and look at it, as recommended in Staying safe:

$ curl -fsSL -o install.sh \
    https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh
$ less install.sh          # have a look (q to quit)
$ sh install.sh
$ rm install.sh

The installer puts Oh My Zsh in ~/.oh-my-zsh and creates a new ~/.zshrc. If you already had one, it's saved as ~/.zshrc.pre-oh-my-zsh.

Step 3: Get to know ~/.zshrc

~/.zshrc is to Zsh what ~/.bashrc is to Bash: it's read every time you open a terminal. The two most important lines are near the top:

ZSH_THEME="robbyrussell"       # how the prompt looks
plugins=(git)                  # which plugins are switched on

After every change, reload it with omz reload (or open a new terminal).

Themes

Oh My Zsh comes with over 100 themes. You can browse them with pictures on the Themes wiki page, or let it pick:

ZSH_THEME="random"            # a different theme in every new terminal…
$ echo $RANDOM_THEME          # …this shows which one you got, so you can keep it
ZSH_THEME="agnoster"          # then set the one you liked

Fancy themes like agnoster use special symbols that need a Nerd Font (or Powerline font). Without one, you'll see boxes or question marks. Download one from nerdfonts.com (for example "JetBrainsMono Nerd Font" or "MesloLGS Nerd Font"; on Arch: sudo pacman -S ttf-jetbrains-mono-nerd), then choose it in your terminal's preferences.

Built-in plugins worth switching on

These come with Oh My Zsh. Just add their names to the plugins=( ) line, separated by spaces:

plugins=(git sudo z extract colored-man-pages command-not-found)
PluginWhat it gives you
gitShort aliases: gst = git status, ga = git add, gcmsg "msg" = git commit -m, gp = git push, gl = git pull. Run alias | grep git to see them all.
sudoForgot sudo? Press Esc twice and it's added to the start of the line.
zJump to folders you use often by part of their name: z proj β†’ ~/Documents/Projects.
extractOne command for every archive type: extract file.tar.gz, extract photos.zip, extract backup.7z.
colored-man-pagesManual pages (man ls) in colour, so they're easier to read.
command-not-foundSuggests which package to install when a command doesn't exist.

Oh My Zsh also adds handy shortcuts without any plugin: d lists the last folders you visited, numbered, and typing just that number (e.g. 2) jumps back there. - goes to the previous folder.

The two most popular extra plugins

These aren't included with Oh My Zsh, but almost everyone adds them:

$ cd ~/.oh-my-zsh/custom/plugins
$ git clone https://github.com/zsh-users/zsh-autosuggestions
$ git clone https://github.com/zsh-users/zsh-syntax-highlighting
$ cd

Then add them to your plugin list. zsh-syntax-highlighting must be last:

plugins=(
  git sudo z extract colored-man-pages command-not-found
  zsh-autosuggestions
  zsh-syntax-highlighting
)

A long list can be spread over several lines like this, which makes it easier to read.

Your own aliases and settings

Bring your aliases and PATH changes over from ~/.bashrc (see 3.9). The tidy way is to put them in a file in Oh My Zsh's custom folder. Every .zsh file there is loaded automatically, and it's kept safe during updates:

# ~/.oh-my-zsh/custom/my-aliases.zsh
alias update='sudo apt update && sudo apt upgrade'
alias ll='ls -lah'
export PATH="$HOME/.local/bin:$PATH"

A modern prompt: Starship

Starship is a fast, good-looking prompt that works in Zsh, Bash and other shells, so your prompt looks the same everywhere. It shows the Git branch, programming language versions, how long a command took and more, only when relevant. Install it (Arch: sudo pacman -S starship; other distros: see starship.rs), set ZSH_THEME="", and add this as the last line of ~/.zshrc:

eval "$(starship init zsh)"

It looks best with a Nerd Font. You may also come across Powerlevel10k, a very popular Zsh theme. It still works, but its author now describes it as having very limited support.

Keeping it fast and tidy

$ omz update                         # update Oh My Zsh
$ omz plugin list                    # see all available plugins
$ time zsh -i -c exit                # how long a new terminal takes to start

Oh My Zsh also offers to update itself every couple of weeks. Every plugin adds a little start-up time. If new terminals feel sluggish (more than about half a second), remove plugins you don't use.

Try it

Install Zsh and Oh My Zsh, turn on sudo, z, zsh-autosuggestions and zsh-syntax-highlighting, then:

  1. Type apt instal (with a typo) and watch it turn red. Fix it and watch it turn green.
  2. Type cat /etc/os-release, press Enter, then type cat /e and accept the grey suggestion with β†’.
  3. Visit a few folders, then type d and jump back with a number.
Changed your mind?

Run uninstall_oh_my_zsh to remove Oh My Zsh (it restores your old ~/.zshrc), and chsh -s $(which bash) to go back to Bash. Log out and in again afterwards.

Other options: fish is a shell with autosuggestions and colours built in and no setup needed, but its scripting language differs from Bash. Lighter Zsh plugin managers like antidote or zinit start faster than Oh My Zsh, but take a little more setting up.

3.11 Writing shell scripts

A shell script is simply a text file containing commands you'd otherwise type by hand. It's the first step into automating your computer.

Your first script

Create ~/.local/bin/backup-docs with nano:

#!/bin/bash
# backup-docs β€” copy my Documents to a USB drive named BACKUP

set -euo pipefail    # stop at the first error

DEST="/media/$USER/BACKUP"

if [ ! -d "$DEST" ]; then
    echo "Backup drive not found at $DEST. Is it plugged in?" >&2
    exit 1
fi

echo "Backing up Documents to $DEST ..."
rsync -ah --info=progress2 "$HOME/Documents/" "$DEST/Documents/"
echo "Done at $(date '+%H:%M on %d %b %Y')."

Make it runnable, then run it:

$ chmod +x ~/.local/bin/backup-docs
$ backup-docs

What each part means

Loops: doing something to many files

#!/bin/bash
# Convert every PNG in the current folder to JPG (needs ImageMagick)
for file in *.png; do
    magick "$file" "${file%.png}.jpg"
    echo "Converted $file"
done

${file%.png} means "the value of file with .png removed from the end".

Careful: always quote your variables

Write "$file", not $file. Without quotes, a file called My Photo.png is treated as two files, My and Photo.png. That's at best an error, and with rm a disaster. The free tool shellcheck finds mistakes like this in your scripts.

3.12 Scheduling tasks

cron: the classic scheduler

Run crontab -e to edit your personal schedule. Each line is: minute hour day-of-month month day-of-week command. * means "every".

# m  h  dom mon dow  command
  0  3   *   *   *   /home/anna/.local/bin/backup-docs     # every day at 03:00
 30  9   *   *   1   /home/anna/.local/bin/weekly-report   # Mondays at 09:30
*/15 *   *   *   *   /home/anna/.local/bin/check-site      # every 15 minutes

The website crontab.guru translates these lines into plain English. Note: some distros (like Fedora and Arch) need the cronie package installed first.

systemd timers: the modern alternative

systemd can also run jobs on a schedule, with better logging (journalctl) and the ability to catch up on jobs missed while the computer was off. They take a little more setup: a .service file describing the job and a .timer file describing when. List existing ones with:

$ systemctl list-timers

3.13 Troubleshooting

Almost every problem can be fixed without reinstalling. Work through these calmly.

The desktop froze

  1. Wait 30 seconds. A program may be busy.
  2. Press Ctrl+Alt+F3 to switch to a text console. Log in with your username and password.
  3. Find and kill the culprit with htop, or restart the graphical session with sudo systemctl restart display-manager (unsaved work in open apps is lost).
  4. Return to the desktop with Ctrl+Alt+F1 or F7, depending on the distro.

It won't start after an update

  1. Restart and open the GRUB menu. If it doesn't appear, hold Shift or tap Esc while the computer starts.
  2. Choose Advanced options and pick an older kernel. If that works, the new kernel or driver is the problem, often NVIDIA. Wait for a fix or reinstall the driver.
  3. Or choose recovery mode, which offers a repair menu and a root shell.
  4. Or use Timeshift to go back to yesterday's snapshot. It works from a Live USB too.

The disk is full

$ df -h                               # which drive is full?
$ ncdu /                              # what's using the space?
$ sudo apt clean                      # delete downloaded package files
$ sudo apt autoremove                 # remove unused packages and old kernels
$ flatpak uninstall --unused          # remove unused Flatpak runtimes
$ sudo journalctl --vacuum-time=2weeks   # shrink old logs

Old Timeshift snapshots can also take a lot of space. Delete some from the Timeshift app.

Rescuing files when nothing else works

Boot from a Live USB. Your internal disk appears in the Files app, and you can copy your files to an external drive. As long as the disk itself isn't broken, your data is almost always recoverable this way.

A general method

  1. What changed? A recent update, new software or a settings change is the usual suspect.
  2. Read the error message, exactly as written, and search for it with your distro's name.
  3. Check the logs: journalctl -b -p err and sudo dmesg.
  4. Change one thing at a time, and note what you did so you can undo it.

3.14 Where to go next

Level 3 checklist

Congratulations: you've completed the course! πŸŽ‰