Lesson 04 beginner

Working with Files and Directories

Create, copy, move, link, find, edit, archive and delete files on a Linux server without nasty surprises, from mkdir -p and cp -a to symlinked releases, find -exec, the vim survival kit, tar with zstd and sha256sum checks.

Every deployment, backup and cleanup job is, underneath, a handful of file operations: create a directory, copy a release, switch a link, archive the old one, delete what is no longer needed. The commands are short and fast, and that is exactly the danger. Linux has no recycle bin, rm does not ask twice, and a stray space in a path can wipe the wrong directory.

In this lesson you learn the everyday file commands with the flags that make them safe, how links work and why deploy tools rely on them, how to find files by name, size and age, how to survive in nano and vim, and how to pack and verify archives. A container or WSL is enough for everything here.

If you skipped ahead: recreate Orbit’s layout with sudo mkdir -p /srv/orbit/{api,public,releases} /etc/orbit /var/log/orbit /var/backups/orbit and a sample config with printf 'ORBIT_PORT=3000\nORBIT_LOG_LEVEL=info\n' | sudo tee /etc/orbit/orbit.env

Creating files and directories

touch creates an empty file, or updates the timestamp of one that exists. mkdir creates a directory, and with -p it creates every missing parent and does not complain if the directory is already there, which makes it safe to rerun in scripts:

$ touch notes.txt
$ mkdir projects/orbit/docs
mkdir: cannot create directory 'projects/orbit/docs': No such file or directory
$ mkdir -p projects/orbit/docs
$ ls -d projects/orbit/docs
projects/orbit/docs

Copying with cp

cp source destination copies a file. The flags decide what else comes along:

FlagMeaningUse it when
-rCopy directories recursivelyCopying a folder
-aArchive mode: recursive, and keeps permissions, owner, group, timestamps and linksBackups and anything under /etc or /srv
-iAsk before overwriting an existing fileWorking by hand

The difference between -r and -a bites people on servers. A plain copy made with sudo belongs to root and loses its group, so a service may suddenly be unable to read it. Back up configuration with -a, shown here on orbit-web-01, where the file belongs to the orbit group:

$ sudo cp -a /etc/orbit/orbit.env /etc/orbit/orbit.env.bak
$ ls -l /etc/orbit
-rw-r----- 1 root orbit 48 Nov  3 10:20 orbit.env
-rw-r----- 1 root orbit 48 Nov  3 10:20 orbit.env.bak

The trailing-directory trap

When the destination is an existing directory, cp -r puts the source inside it. When it does not exist, the copy becomes it. Run the same command twice and the result differs:

$ cp -r /srv/orbit/public /tmp/site
$ cp -r /srv/orbit/public /tmp/site
$ ls /tmp/site
index.html  public

The second run created /tmp/site/public. To copy the contents of a directory into another one reliably, use cp -a /srv/orbit/public/. /tmp/site/. (rsync -a src/ dest/, which you will meet later, has the same subtlety: a trailing slash on the source means “the contents”.)

Moving and renaming with mv

There is no rename command: renaming is moving to a new name in the same place.

$ mv notes.txt meeting-notes.txt
$ mv meeting-notes.txt projects/orbit/docs/

Within one filesystem, mv only changes a directory entry, so it is instant even for a 50 GB file. Across filesystems (for example from /tmp to a mounted data disk) it copies and then deletes. Like cp, it overwrites silently unless you add -i or -n.

Deleting with rm and rmdir

rm file deletes a file, rm -r dir deletes a directory and everything in it (-r recurses), and rmdir dir deletes a directory only if it is empty, a safe way to tidy up. -i asks before every file, -I asks once when you delete more than three files or recurse, and -f never asks and ignores missing files: it is for scripts, not for your fingers.

Why rm -rf is feared

rm -rf removes a whole tree without a single question, and there is no undo. Real outages come from tiny slips:

  • A space in the wrong place: rm -rf /srv/orbit /releases deletes /srv/orbit and /releases.
  • An empty variable in a script: rm -rf "$RELEASE_DIR"/* becomes rm -rf /* when the variable is unset.
  • The wrong current directory: rm -rf * in / instead of /tmp/build.

rm refuses to delete / itself by default (--preserve-root), but that does not protect /*, /etc or /srv. Protect yourself with habits:

  • Run ls with exactly the same path or pattern first, then press Up and replace ls with rm.
  • Prefer absolute paths and check the prompt with pwd before deleting with a relative one.
  • Use rm -I by hand; never alias your way out of thinking.
  • In scripts, write "${RELEASE_DIR:?}", which stops the script with an error if the variable is empty, and start scripts with set -u (lesson 12).
  • Keep real backups or snapshots. They are the only true undo.

Wildcards and brace expansion

The globbing patterns from lesson 3 work with every command: ls /var/log/orbit/*.log.[0-9].gz shows exactly what sudo rm /var/log/orbit/*.log.[0-9].gz would delete, so run the ls first.

Brace expansion is a different feature: the shell generates words from a list or a range, whether or not the files exist.

$ echo report-{dev,staging,prod}.txt
report-dev.txt report-staging.txt report-prod.txt
$ sudo cp -a /etc/orbit/orbit.env{,.bak}

The last line expands to cp -a /etc/orbit/orbit.env /etc/orbit/orbit.env.bak, the classic one-line backup before an edit. Use echo first whenever you are not sure what an expansion produces.

Hard links, symbolic links and inodes

On disk, a file’s data and metadata (owner, mode, size, where the blocks are) live in an inode. A filename is just a directory entry pointing to an inode number. That gives you two kinds of link:

  • A hard link is a second name for the same inode. Both names are equal; the data stays until the last name is deleted.
  • A symbolic link (symlink) is a tiny file that contains a path. Follow the path and you reach the target; delete the target and the link dangles.
$ echo hello > a.txt
$ ln a.txt b.txt
$ ln -s a.txt c.txt
$ ls -li
1835015 -rw-rw-r-- 2 ubuntu ubuntu 6 Nov  3 10:10 a.txt
1835015 -rw-rw-r-- 2 ubuntu ubuntu 6 Nov  3 10:10 b.txt
1835021 lrwxrwxrwx 1 ubuntu ubuntu 5 Nov  3 10:10 c.txt -> a.txt
$ rm a.txt
$ cat b.txt
hello
$ cat c.txt
cat: c.txt: No such file or directory

-i prints the inode number first: a.txt and b.txt share one, and the 2 is the link count. (echo hello > a.txt writes text into a file; lesson 5 covers redirection.)

Hard link (ln)Symbolic link (ln -s)
Points toThe inode itselfA path
Works for directoriesNoYes
Crosses filesystemsNoYes
If the original name is deletedData survivesLink breaks
Typical useBackup tools, deduplicationReleases, versions, config switches

The release symlink pattern

Orbit deploys each version into its own directory and points one symlink, current, at the live one. Services and nginx only ever use /srv/orbit/current:

$ sudo mkdir -p /srv/orbit/releases/{2026.11.1,2026.11.2}
$ sudo ln -s /srv/orbit/releases/2026.11.1 /srv/orbit/current
$ ls -l /srv/orbit/current
lrwxrwxrwx 1 root root 29 Nov  3 10:30 /srv/orbit/current -> /srv/orbit/releases/2026.11.1
$ sudo ln -sfn /srv/orbit/releases/2026.11.2 /srv/orbit/current
$ readlink /srv/orbit/current
/srv/orbit/releases/2026.11.2

-s makes a symlink, -f replaces an existing one, and -n treats the existing link as a file instead of descending into the directory it points to (without -n, the new link lands inside the old release). Rolling back is the same command with the old version. Deploy tools go one step further and switch atomically, so there is never a moment without a current: create the link under a temporary name, then rename it over the old one with ln -s /srv/orbit/releases/2026.11.2 /srv/orbit/current.new and mv -T /srv/orbit/current.new /srv/orbit/current.

Finding files with find

find walks a directory tree and tests every entry. The basic form is find <where> <tests> <action>:

$ find /etc -maxdepth 1 -type f -name '*.conf'
/etc/adduser.conf
/etc/ld.so.conf
/etc/sysctl.conf
$ find /var/log/orbit -type f -mtime +14
/var/log/orbit/api.log.3.gz
TestMatches
-name '*.log' / -inameName pattern (case-insensitive with -iname); always quote it
-type f, -type d, -type lRegular files, directories, symlinks
-size +100M, -size -1kLarger than 100 MiB, smaller than 1 KiB
-mtime +14, -mtime -1Modified more than 14 days ago, within the last day

Quote patterns so the shell does not expand them before find sees them, and put options such as -maxdepth before the tests. To act on the results, use -exec: {} stands for the file name, and the command ends with \; (once per file) or + (many files per command, faster):

$ sudo find /srv/orbit -type f -name '*.sh' -exec chmod 755 {} +
$ sudo find /var/log/orbit -type f -name '*.gz' -mtime +14 -print
/var/log/orbit/api.log.3.gz
$ sudo find /var/log/orbit -type f -name '*.gz' -mtime +14 -delete

Warning: find evaluates from left to right, and -delete is an action like any other. find /var/log/orbit -delete -name '*.gz' deletes everything first and tests the name afterwards. Always run the command with -print, read the list, then replace -print with -delete at the end.

Editing files: nano and the vim survival kit

Servers rarely have a graphical editor. Learn one simple editor and enough vim to escape.

nano shows its shortcuts at the bottom of the screen (^ means Ctrl). Open a file with sudo nano /etc/orbit/orbit.env, save with Ctrl+O and Enter (recent versions also accept Ctrl+S), exit with Ctrl+X, search with Ctrl+W, cut and paste whole lines with Ctrl+K and Ctrl+U, and undo with Alt+U.

vim (or vi) is installed almost everywhere, including minimal images, so you will land in it eventually, often because git or crontab -e opened it. It starts in Normal mode, where keys are commands, not text:

KeysAction
iEnter Insert mode and type text
EscBack to Normal mode
:wSave
:q / :q!Quit / quit and discard changes
:wq or ZZSave and quit
dd / uDelete the current line / undo

If vim seems to ignore you, press Esc twice, then type :q! and Enter. On Ubuntu, sudo update-alternatives --config editor chooses the default editor for tools that open one.

Archives and checksums

tar

tar packs a directory into one file, optionally compressed. The letters after the dash form a little sentence:

FlagMeaning
c / x / tCreate / extract / list (table of contents)
fThe archive file name follows
z / J / --zstdCompress with gzip / xz / zstd
-C dirChange to dir first
$ sudo tar --zstd -cf /var/backups/orbit/public-2026-11-03.tar.zst -C /srv/orbit public
$ tar -tf /var/backups/orbit/public-2026-11-03.tar.zst
public/
public/index.html
$ mkdir -p /tmp/restore
$ tar -xf /var/backups/orbit/public-2026-11-03.tar.zst -C /tmp/restore

Swap --zstd for z (and the .tar.gz suffix) to get a gzip archive. -C /srv/orbit public stores the paths as public/... instead of /srv/orbit/public/..., so the archive unpacks wherever you want. When extracting, GNU tar detects the compression by itself. zstd compresses about as well as gzip at a fraction of the time (and decompresses very fast), which is why package formats and backup tools moved to it; install the zstd package if --zstd complains. Always list (-t) an archive from someone else before extracting it, to see where the files will land.

sha256sum and diff

A checksum proves a file arrived intact, or that a download is the one the vendor published:

$ cd /var/backups/orbit
$ sha256sum public-2026-11-03.tar.zst | sudo tee public-2026-11-03.tar.zst.sha256
9c1e4b0d7a52f3e8...b81f  public-2026-11-03.tar.zst
$ sha256sum -c public-2026-11-03.tar.zst.sha256
public-2026-11-03.tar.zst: OK

(tee writes its input to a file; sudo is needed because the directory belongs to root.) Any changed byte turns OK into FAILED. Prefer SHA-256 over MD5 and SHA-1, which are broken for security purposes. diff shows what changed between two files or two release directories:

$ sudo diff -u /etc/orbit/orbit.env.bak /etc/orbit/orbit.env
--- /etc/orbit/orbit.env.bak
+++ /etc/orbit/orbit.env
@@ -1,2 +1,2 @@
 ORBIT_PORT=3000
-ORBIT_LOG_LEVEL=info
+ORBIT_LOG_LEVEL=debug
$ diff -rq /srv/orbit/releases/2026.11.1 /srv/orbit/releases/2026.11.2
Files /srv/orbit/releases/2026.11.1/index.html and /srv/orbit/releases/2026.11.2/index.html differ
Only in /srv/orbit/releases/2026.11.2: robots.txt

-u prints the unified format you know from Git (lines with - removed, + added), -r compares directories recursively and -q only names the files that differ. (Real diff -u headers also show timestamps.)

Red Hat and Alpine

The commands are identical on Rocky Linux and RHEL, with two practical notes. Minimal installs ship vi but not nano (sudo dnf install nano). And with SELinux, mv keeps a file’s original security label while cp gives the copy the label of its new location, so a file moved from a home directory into a web directory may be refused; sudo restorecon -Rv <dir> fixes the labels. On Alpine, cp, find and tar are BusyBox versions with fewer options; apk add coreutils findutils tar zstd installs the full tools when a script needs them.

Practice lab

Orbit’s team wants a safe, repeatable layout for releases and backups on your lab machine.

  1. Create two releases, /srv/orbit/releases/2026.11.1 and 2026.11.2, each with an index.html containing its version, and point /srv/orbit/current at the first one. Then switch to the second and roll back.
  2. Back up /etc/orbit/orbit.env keeping its owner and mode, change the log level to debug with nano, and show the difference.
  3. Archive /srv/orbit/releases with zstd into /var/backups/orbit, store its SHA-256 checksum next to it and verify it.
  4. Create three fake old logs with sudo touch -d '2026-10-01' /var/log/orbit/api.log.{1..3}.gz and one new one, then delete only the logs older than 14 days, previewing first.
Show a solution

Run sudo mkdir -p /srv/orbit/releases/{2026.11.1,2026.11.2}, then echo 2026.11.1 | sudo tee /srv/orbit/releases/2026.11.1/index.html (and the same for the second), sudo ln -s /srv/orbit/releases/2026.11.1 /srv/orbit/current, switch with sudo ln -sfn /srv/orbit/releases/2026.11.2 /srv/orbit/current and roll back with the same command and the old path, checking each time with readlink /srv/orbit/current. Back up with sudo cp -a /etc/orbit/orbit.env{,.bak}, edit with sudo nano /etc/orbit/orbit.env and compare with sudo diff -u /etc/orbit/orbit.env.bak /etc/orbit/orbit.env. Archive with sudo tar --zstd -cf /var/backups/orbit/releases.tar.zst -C /srv/orbit releases, then in /var/backups/orbit run sha256sum releases.tar.zst | sudo tee releases.tar.zst.sha256 and sha256sum -c releases.tar.zst.sha256. Finally sudo touch /var/log/orbit/api.log.gz, preview with sudo find /var/log/orbit -type f -name '*.gz' -mtime +14 -print (three files) and rerun it with -delete instead of -print.

Exercise

Maya backs up the config with sudo cp /etc/orbit/orbit.env /tmp/orbit.env and later copies it back the same way. Now the API (running as orbit) cannot read it. What went wrong?

  1. /tmp corrupts files on reboot
  2. A plain cp run as root creates files owned by root:root, so the orbit group lost read access; cp -a would have kept owner, group and mode
  3. cp always makes files executable
  4. The file was hard-linked instead of copied
Show answer

Answer: B. Without -a (or -p), cp creates a new file owned by the user running it. Run as root, the group becomes root and the orbit service account loses access. Archive mode preserves ownership, permissions and timestamps.

Exercise

Release 2026.11.2 is live through /srv/orbit/current and the API returns errors. The previous release is still in /srv/orbit/releases/2026.11.1. What is the fastest safe rollback?

  1. sudo rm -rf /srv/orbit/current and copy the old release into its place
  2. sudo cp -r /srv/orbit/releases/2026.11.1 /srv/orbit/current
  3. sudo ln -sfn /srv/orbit/releases/2026.11.1 /srv/orbit/current
  4. sudo mv /srv/orbit/releases/2026.11.1 /srv/orbit/current
Show answer

Answer: C. Re-pointing the symlink is instant and keeps both releases intact. rm -rf on a path you meant as a link is risky, cp -r would copy into the directory the link points to, and mv would move the old release itself out of releases/ instead of switching the link.

Exercise

Leo needs to remove compressed Orbit logs older than 30 days from /var/log/orbit. Which approach is the safe one?

  1. sudo find /var/log/orbit -delete -name '*.gz' -mtime +30
  2. sudo rm -rf /var/log/orbit/*
  3. Run sudo find /var/log/orbit -type f -name '*.gz' -mtime +30 -print, check the list, then rerun it with -delete in place of -print
  4. sudo find /var/log/orbit -name *.gz -mtime +30 -delete without quotes
Show answer

Answer: C. find evaluates left to right, so -delete before the tests deletes everything. Previewing with -print, quoting the pattern and putting -delete last is the reliable pattern.

Key takeaways

  • mkdir -p is safe to rerun; cp -a keeps owners, modes and timestamps; mv renames and moves.
  • rm has no undo: preview with ls, use absolute paths, guard script variables with ${VAR:?}, keep backups.
  • Hard links are extra names for an inode; symlinks are pointers to a path, and they power the current release pattern with ln -sfn.
  • find filters by name, type, size and age; preview with -print before -delete or -exec.
  • Edit with nano, escape vim with Esc and :q!; archive with tar -C and zstd, verify with sha256sum -c, compare with diff -u.

FAQ

Can I recover a file deleted with rm?

Not reliably. rm removes the directory entry and the space is reused quickly, so recovery tools are a long shot and never something to plan on. If a running process still has the file open, you can sometimes copy it back from /proc/<PID>/fd/. The real answer is backups, snapshots and version control.

What is the difference between cp -r and cp -a?

cp -r copies directories recursively but creates new files owned by you with default timestamps. cp -a (archive) also preserves ownership, permissions, timestamps and symlinks, so the copy is a faithful clone. Use -a for backups, migrations and anything a service will read.

Why did cp -r copy my folder inside the destination folder?

Because the destination already existed. cp -r src dest creates dest if it is missing, but copies into dest/src if dest is already a directory. To copy only the contents, use cp -a src/. dest/; with rsync, use a trailing slash on the source: rsync -a src/ dest/.

How do I find large files that are filling the disk?

Run sudo find / -xdev -type f -size +500M to list big files on the root filesystem (-xdev stops at mount points), or sudo du -xh --max-depth=1 / | sort -h to rank directories by size. Start with /var on a server. Lesson 11 and lesson 18 cover disk and log cleanup in depth.

Should I use gzip, xz or zstd for tar archives?

For backups and transfers in 2026, zstd is the best default: it is much faster than xz and gzip at similar or better compression. gzip is the most widely supported and fine for small archives. xz squeezes a little more out of the data but is slow, so it suits files that are compressed once and downloaded many times.

↑ ↓ navigate Enter open Esc close