# The shell and the filesystem

Read a prompt, find your way around the Linux directory tree, and create, copy, move and delete files without breaking anything.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 1. About 20 minutes, beginner. Source: https://devops.rajeev.pro/courses/linux/01-shell-and-filesystem

## What you will learn

- Explain what the shell is and read every part of a prompt
- Know where Linux keeps config, logs, programs and your own files
- Move around with absolute and relative paths, and know when to use each
- Create, copy, move and delete files and folders safely

## What the shell actually is

Before remote servers were common, an administrator could sit at a machine and click through its
desktop. On a production Linux server, there may be no desktop at all. A teammate needs to inspect
logs, restart a service or make a careful file change over a text connection. Clicking is not an
option, and repeating those steps by hand is easy to get wrong.

A **shell** is a program that reads a command, runs it and displays the result. Bash is common on
Linux servers; zsh is common on developer Macs. A terminal is the text interface where you interact
with the shell. The shell parses your words into a program, options and arguments, then starts that
program and shows its output. That makes the same small set of commands useful on your laptop, a
remote server and in a script.

In this lesson, you'll read a prompt safely, find your place in the filesystem, and practise
creating, copying, moving and deleting files without losing track of the target.

Before you type anything, read the prompt. It tells you who you are, where you are and how
careful you need to be:

```sh
rajeev@web-01:~/app$
```

| Part      | Means                                                                       |
| --------- | --------------------------------------------------------------------------- |
| `rajeev`  | The user you're logged in as                                                |
| `web-01`  | The machine's hostname. Check it before you delete anything on a server     |
| `~/app`   | The directory you're in. `~` is short for your home directory               |
| `$` / `#` | `$` for a normal user, `#` for **root**, who can change anything on the box |

A command is a program name, then options (usually starting with `-`), then arguments:

```sh
$ ls -l /etc/hostname      # program: ls · option: -l (long format) · argument: /etc/hostname
-rw-r--r-- 1 root root 7 Mar  2 09:14 /etc/hostname
$ whoami                   # who am I logged in as?
rajeev
$ ls --help | head -n 5    # almost every command explains itself with --help
```

> **Tab completion saves you hours.** Type the first few letters of a command or path and press **Tab**. The shell finishes it, or shows the options when there's more than one. It's faster, and it means fewer typos in paths.

## How the filesystem is laid out

Linux has **one tree**, starting at `/` (called "root"). There are no `C:` or `D:` drives:
extra disks are attached as folders somewhere inside the tree. Every server you log in to uses
roughly the same layout, so once you learn it you know where to look on any of them.

> **Figure.** The Linux directory tree: / at the top, with /etc for config, /var/log for logs, /home for users, /usr/bin for programs, /opt for extra software, /tmp for temporary files and /proc for live kernel information.
>
> One tree from /. Learn these seven folders and you can find your way round any Linux server.

| Path                         | What lives there                                                | You go there to                    |
| ---------------------------- | --------------------------------------------------------------- | ---------------------------------- |
| `/etc`                       | System-wide configuration: `nginx/`, `ssh/sshd_config`, `hosts` | Change how a service behaves       |
| `/var/log`                   | Log files, written by services as they run                      | Find out what went wrong           |
| `/home/<user>`               | Each user's own files. Root's home is `/root`                   | Keep your scripts and notes        |
| `/usr/bin`, `/usr/local/bin` | Programs. Packages go in `/usr/bin`, your own installs in local | See where a command comes from     |
| `/opt`                       | Software installed outside the package manager                  | Find a vendor's app                |
| `/tmp`                       | Temporary files, often cleared on reboot                        | Scratch work you can lose          |
| `/proc`                      | Not real files: live information from the kernel                | Read CPU, memory and process facts |

Try `cat /proc/cpuinfo` or `cat /proc/meminfo`. Nothing is stored on disk there; the kernel
writes the answer the moment you read it.

> **Video.** [The Linux File System Explained | Understanding Linux Directories](https://www.youtube.com/watch?v=e56dgj9_sSE) (Akamai Developers)

## Moving around

```sh
$ pwd                # print working directory: where am I?
/home/rajeev
$ ls                 # what's here?
$ ls -la             # long format, including hidden files (names starting with .)
$ cd /var/log        # go to an absolute path
$ cd ..              # up one level, to /var
$ cd -               # back to the previous directory, /var/log
$ cd                 # no argument: straight home
```

> **Figure.** Animated. You start in /home/rajeev. cd /var/log moves you to /var/log. cd .. goes up one level to /var. cd - jumps back to the previous directory, /var/log. cd with no argument goes straight home to /home/rajeev. A panel shows what pwd prints at each step.
>
> The same commands, animated: watch where each cd takes you, and what pwd prints.

There are two ways to write a path, and you'll use both every day:

- An **absolute** path starts with `/` and works from anywhere: `/var/log/nginx/error.log`.
- A **relative** path starts from where you are now. `.` is the current directory and `..` is the one above it. From `/var/www`, `../log` means `/var/log`.

Use absolute paths in scripts, cron jobs and config files, because they don't depend on where
the command happens to run. Use relative paths when you're moving around by hand.

> **Video.** [Linux Command Line Tutorial For Beginners 3 - cd command in Linux](https://www.youtube.com/watch?v=FTTr2bjI2UM) (ProgrammingKnowledge)

## Create, copy, move and delete

When a release needs a new folder or a backup copy, the shell lets you make that change explicitly
and repeat it later. `mkdir` creates directories, `touch` creates an empty file (or updates an
existing file's timestamp), `cp` copies, `mv` moves or renames, and `rm` removes files. These commands
act on the paths you give them; they do not ask whether you meant a nearby file.

```sh
$ mkdir -p ~/projects/demo/logs      # -p creates every missing parent folder, no error if it exists
$ cd ~/projects/demo
$ touch notes.txt                    # create an empty file (or update an existing file's time)
$ cp notes.txt notes.bak             # copy a file
$ cp -r logs logs-old                # copy a folder and everything in it: -r means recursive
$ mv notes.bak archive.txt           # rename...
$ mv archive.txt logs/               # ...or move. mv does both
$ rm archive.txt                     # fails: it's in logs/ now
rm: cannot remove 'archive.txt': No such file or directory
$ rm logs/archive.txt                # delete a file
$ rmdir logs-old                     # delete a folder, only if it's empty
$ rm -r logs-old                     # delete a folder and everything in it
```

`-p` on `mkdir` creates missing parent directories and tolerates an already-existing path.
`-r` means recursive: `cp -r` walks a directory tree to copy it, and `rm -r` walks it to remove it.
The `mv` command uses the destination to decide whether to rename a file or place it inside a
directory. In the example, `archive.txt` moves into `logs/`, so the following `rm archive.txt`
fails because that path no longer exists. The failure is useful feedback: check `pwd` and `ls` to
find the file's actual location before trying again.

Use `cp` when you need to preserve the original while editing a copy. Use `mv` for an intentional
rename or move. Prefer `rmdir` for a directory that should be empty; it refuses to remove one that
still contains files. `rm -r` is appropriate only when you have verified the exact tree to remove.
The common mistake is running a recursive command from an unexpected directory or with a broad
path. Read the command all the way through and inspect its target first.

> **There is no recycle bin.** `rm` deletes straight away. There's no Trash and no undo. Before any `rm -r`, run `ls` on the same path to see exactly what you're about to delete, or use `rm -ri` to be asked about every file. Never paste an `rm` command you haven't read to the end.

### Read files without opening an editor

| Command           | Use it to                                                 |
| ----------------- | --------------------------------------------------------- |
| `cat file`        | Print a short file in one go                              |
| `less file`       | Scroll through a long file. `/word` searches, `q` quits   |
| `head -n 20 file` | See the first 20 lines                                    |
| `tail -n 50 file` | See the last 50 lines, where the newest log entries are   |
| `tail -f file`    | Keep following a log as new lines arrive. Ctrl+C stops it |

### Find files

```sh
$ find /etc -name "*.conf"           # every .conf file under /etc
$ find ~/projects -mtime -1          # files changed in the last 24 hours
$ find /var/log -name "*.log" -size +10M   # logs bigger than 10 MB
```

> **In production.** When you're on a live server, slow down. Check the hostname in the prompt, `pwd` before you delete, and copy a config file (`cp nginx.conf nginx.conf.bak`) before you change it. Thirty seconds of checking is cheaper than an hour of restoring.

## Mission: Lay out a release folder

You're shipping version 1.4 of an app. Create ~/deploy/releases/1.3, ~/deploy/releases/1.4 and ~/deploy/shared/logs in one command. Copy /etc/hostname and /etc/os-release into the 1.4 release as a record of the machine. Then check what's inside the old 1.3 release and remove it safely.

- You need: /etc/hostname, /etc/os-release
- You'll have: ~/deploy/releases/1.4/

```sh
$ mkdir -p ~/deploy/releases/{1.3,1.4} ~/deploy/shared/logs   # {1.3,1.4} expands to both names
$ cp /etc/hostname /etc/os-release ~/deploy/releases/1.4/
$ find ~/deploy -type f                  # every file, so you know what's there
/home/rajeev/deploy/releases/1.4/hostname
/home/rajeev/deploy/releases/1.4/os-release
$ ls -la ~/deploy/releases/1.3           # look before you delete
$ rm -r ~/deploy/releases/1.3
$ ls ~/deploy/releases
1.4
```

`cp` takes several files and copies them all into the last argument, as long as it's a folder.
Listing `1.3` before deleting it is the habit that saves you on the day the folder isn't empty.

## Try it

- Create `~/lab1/logs` with one command.
- Copy `/etc/hostname` and `/etc/os-release` into `~/lab1/logs`.
- Show only the first three lines of your copy of `os-release` with `head`.
- From `~/lab1/logs`, go to `/var/log` with `cd`, then come straight back with `cd -`.
- List every `.conf` file directly inside `/etc` with `find`.
- Look inside `~/lab1` with `ls -R`, then delete it.

## Quiz

1. You restart a service and want to watch its log file as new lines arrive. Which command do you run?
   - cat app.log
   - **tail -f app.log** (answer)
   - head -n 50 app.log
   Why: `tail -f` prints the last lines and then keeps following the file, so you see new lines the moment they are written. Stop it with Ctrl+C.

2. Where would you look first for nginx's configuration?
   - /var/log/nginx
   - /home/nginx
   - **/etc/nginx** (answer)
   Why: System-wide configuration lives under `/etc`. Logs go to `/var/log`, and `/home` holds users' own files.

3. You're in /var/www. What is the relative path to /var/log?
   - **../log** (answer)
   - ./log
   - /log
   Why: `..` goes up one level to `/var`, then `log` goes down into `/var/log`. `./log` would mean `/var/www/log`, and `/log` is an absolute path at the root.

4. Your prompt ends in `#` instead of `$`. What does that tell you?
   - You're in your home directory
   - **You're root, so every command can change anything on the system** (answer)
   - The last command failed
   Why: By convention `#` means the root user. Read commands twice before you press Enter, then leave the root shell as soon as you're done.

5. You ran `rm notes.txt` by mistake. How do you get it back?
   - Look in the Trash folder
   - Run `rm --undo notes.txt`
   - **Restore it from a backup or from Git; the shell has no recycle bin** (answer)
   Why: `rm` unlinks the file straight away. There is no trash and no undo, which is why you list what you are about to delete first.

## Resources

- [Command line for beginners](https://ubuntu.com/tutorials/command-line-for-beginners) (Ubuntu)
- [Filesystem Hierarchy Standard 3.0](https://refspecs.linuxfoundation.org/FHS_3.0/fhs/index.html) (Linux Foundation)
- [hier(7): the filesystem hierarchy, in the manual](https://manpages.ubuntu.com/manpages/noble/man7/hier.7.html) (Ubuntu manpages)
- [GNU Coreutils (ls, cp, mv, rm and friends)](https://www.gnu.org/software/coreutils/) (GNU)
- [explainshell, paste a command and see every part explained](https://explainshell.com/) (explainshell)
- [tldr pages, short practical examples for every command](https://tldr.inbrowser.app/) (tldr-pages)
