# Working with files: permissions, archives and links

Read and set permissions with confidence, copy and find files in bulk, pack and unpack archives, and use links the way real deployments do.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 4. About 35 minutes, beginner. Source: https://devops.rajeev.pro/courses/linux/04-working-with-files

## What you will learn

- Read any permission string like -rwxr-x--- and set it with chmod in letters or numbers
- Change owners and groups, and explain what x means on a folder
- Explain umask, setuid, setgid and the sticky bit, and find risky setuid files
- Copy, move and select files in bulk with wildcards, find and xargs
- Choose between find and locate, and pass file lists to xargs safely
- Create, list and extract tar archives with gzip or xz
- Explain hard links vs symlinks, and switch a release with a symlink

## Reading permissions

When several people use one server, file permissions decide who can read, change or run each file. Without
that boundary, an ordinary user could change another service's configuration or read a private key.

Linux checks the file's owner, its group and the permissions for everyone else. `ls -l` shows the type, owner,
group and three permission sets. The kernel compares the requesting process's user and groups with those
fields before allowing the operation:

```sh
$ ls -l deploy.sh
-rwxr-x--- 1 rajeev devops 412 Oct 13 10:42 deploy.sh
```

> **Figure.** The permission string -rwxr-x--- decoded. The first character is the type: dash for a file, d for a directory, l for a link. Then three groups of three: the owner has rwx, read write execute, worth 4 plus 2 plus 1 equals 7. The group has r-x, 4 plus 1 equals 5. Others have three dashes, 0. Together that's 750.
>
> Three sets of three. r = 4, w = 2, x = 1: add them per set to get the number.

| Bit | On a file           | On a folder                            |
| --- | ------------------- | -------------------------------------- |
| `r` | read the contents   | list the names inside (`ls`)           |
| `w` | change the contents | create, delete and rename files inside |
| `x` | run it as a program | enter it (`cd`) and reach the files    |

The folder rules surprise people: to delete a file you need `w` on the **folder**, not the file.

> **Video.** [Linux File Permissions: chmod, umask & ACLs Explained | Linux Basics](https://www.youtube.com/watch?v=o_2aXxEqtao&t=39s) (WhiteboardDoodles)

## Changing permissions and owners

Use `chmod` to change the permission bits and `chown` or `chgrp` to change ownership. Start by identifying
which account or service needs access; then grant the smallest read, write or execute permission that supports
that job. Numeric modes combine read (4), write (2) and execute (1) for owner, group and others.

```sh
$ chmod u+x deploy.sh          # letters: add execute for the user (owner)
$ chmod g-w,o-rwx notes.txt    # remove write for the group, everything for others
$ chmod 640 app.env            # numbers: owner rw, group r, others nothing
$ chmod -R g+rX shared/        # recursive; capital X adds x only to folders
$ sudo chown deploy:devops /srv/app   # change owner and group
$ sudo chgrp devops report.csv        # change only the group
```

Symbolic modes such as `u+x` describe a change, while numeric modes such as `640` set all three classes at
once. Use `-R` carefully because it affects every descendant. Uppercase `X` adds execute only to directories
and files that were already executable, which is useful for making a tree traversable without making every
data file a program.

| Number | Letters     | Typical use                                    |
| ------ | ----------- | ---------------------------------------------- |
| `755`  | `rwxr-xr-x` | scripts and programs everyone may run, folders |
| `644`  | `rw-r--r--` | normal files, web pages, most configs          |
| `640`  | `rw-r-----` | configs a service's group must read            |
| `600`  | `rw-------` | secrets: private keys, `.env` files            |
| `700`  | `rwx------` | your private folders, like `~/.ssh`            |

> **Never chmod 777.** 777 lets every user and every process on the machine change the file. It "fixes" a permission error by removing all protection. Find out which user needs access, then give exactly that: the right owner, group, or one extra bit.

### umask: the defaults for new files

New files start from 666 and folders from 777, minus the **umask**. With the common umask
`022`, new files are 644 and folders 755.

```sh
$ umask
0022
$ touch a.txt && mkdir b && ls -ld a.txt b
-rw-r--r-- 1 rajeev rajeev    0 Oct 13 10:50 a.txt
drwxr-xr-x 2 rajeev rajeev 4096 Oct 13 10:50 b
```

### Special bits: setuid, setgid, sticky

| Bit                 | Shows as                                | Means                                                                    |
| ------------------- | --------------------------------------- | ------------------------------------------------------------------------ |
| setuid on a program | `rws` in the owner set                  | runs as the file's owner (`passwd` runs as root to update `/etc/shadow`) |
| setgid on a folder  | `rws` in the group set                  | new files inside get the folder's group: perfect for shared team folders |
| sticky on a folder  | `t` at the end (`/tmp` is `drwxrwxrwt`) | anyone may create files, only the owner may delete them                  |

```sh
$ chmod g+s /srv/shared          # team folder: files inherit the group
$ find / -perm -4000 -type f 2> /dev/null   # audit: every setuid program
```

These bits change the normal owner/group rules and therefore deserve review. Setuid programs run with the
file owner's effective ID; setgid directories pass their group to new files; the sticky bit limits deletion
inside a shared directory. Avoid adding setuid or setgid to an application without understanding its code.
On a team folder, use setgid plus an appropriate group and a suitable umask so new files remain collaborative.
A common mistake is using `chmod -R 777` to silence an error instead of fixing ownership.

A setuid program owned by root that you didn't expect is a security finding. Check the list on
any new server.

> **Video.** [Linux File Permissions: chmod, umask & ACLs Explained | Linux Basics](https://www.youtube.com/watch?v=o_2aXxEqtao&t=124s) (WhiteboardDoodles)

## Copying, moving and selecting in bulk

Bulk commands save time, but a wildcard or `find` expression can match more files than expected. `cp -a`
preserves metadata such as permissions and timestamps; `mv` can rename and move in one operation. Shell
wildcards expand in the shell before the program runs, while `find` walks a directory tree and evaluates each
path.

```sh
$ cp -a /srv/app /srv/app.bak      # -a: keep permissions, owners, times and links
$ mv report.txt reports/2026-10.txt   # move and rename in one step
$ ls *.log                          # wildcard: every name ending in .log
$ ls access.log.?                   # ? = exactly one character
$ ls app-[0-9].conf                 # [ ] = one character from the set
$ cp config.{yml,yml.bak}           # braces expand: cp config.yml config.yml.bak
$ find /var/log -name "*.gz" -mtime +30 -delete          # act on what find matches
$ find . -name "*.log" -size +100M -exec ls -lh {} \;   # run a command on each match
$ find . -name "*.tmp" -print0 | xargs -0 rm             # safe even with spaces in names
```

> **Check before you act.** Run every `find … -delete` or `rm` with a wildcard **without** the action first. `find /var/log -name "*.gz" -mtime +30` shows exactly what would go. Add `-delete` only when the list is right.

For destructive actions, first run the same search without `-delete` or `rm` and inspect every match. Use
`-print0` with `xargs -0` when names may contain spaces, quotes or newlines; the NUL separator cannot occur
inside a filename. Use `-exec … {} \;` when the command should run once per match. A common mistake is piping
plain newline-separated names into `xargs`, which can split a filename into several arguments.

## Finding files with find

`find` walks a folder tree right now and checks every file against your tests. It's slow on a huge disk,
but it's always correct, and it can act on what it finds. The outputs below come from a small practice tree,
`~/lab4`, with an app and some logs.

A `find` command reads left to right: **where** to start, **tests** that must all be true, then an **action**
(`-print` if you give none).

```sh
$ find . -name "*.gz"
./logs/access.log.2.gz
./logs/error.log.3.gz
$ find . -iname "*.LOG"
./logs/access.log
./logs/app.log
$ find . -type f -size +1M
./logs/app.log
$ find logs -name "*.gz" -mtime +30
logs/access.log.2.gz
logs/error.log.3.gz
```

Always quote the pattern. Without quotes, the shell expands `*.gz` in your current folder before `find`
ever sees it.

| Test                       | Matches                                                       |
| -------------------------- | ------------------------------------------------------------- |
| `-name`, `-iname`          | the file name, with wildcards; `-iname` ignores case          |
| `-type f`, `-type d`       | files, folders (`l` for symlinks)                             |
| `-size +1M`, `-size -10k`  | bigger than 1 MiB, smaller than 10 KiB                        |
| `-mtime +30`, `-mmin -15`  | changed more than 30 days ago, less than 15 minutes ago       |
| `-newer FILE`              | changed more recently than FILE                               |
| `-user`, `-group`, `-perm` | owner, group, permission bits (`-perm -o=r`: others can read) |
| `-maxdepth N`              | go at most N folders down                                     |

Tests next to each other mean AND. Use `-o` for OR, with escaped brackets around the group:

```sh
$ find . -type f \( -name "*.tmp" -o -name "*.bak" \)
./app/releases/v1/build.tmp
./app/cache.tmp
./logs/old reports/draft.tmp
$ find . -newer app/releases/v1/index.html -name "*.html"
./app/releases/v2/index.html
$ find app -type f -perm -o=r -name ".env"
app/.env
```

That last one is a real audit: a `.env` file with a password in it that every user on the server can read.

**Skip whole folders with `-prune`.** Searching `node_modules` or `.git` wastes time and floods the output:

```sh
$ find . -name node_modules -prune -o -name "*.js" -print
./app/server.js
```

Read it as: if the name is `node_modules`, don't go in; otherwise, if it ends in `.js`, print it. The
explicit `-print` matters; without it, the pruned folder's name is printed too.

**Act on the matches.** `-printf` formats each line, `-exec … {} +` runs one command with all the matches,
and `-delete` removes them:

```sh
$ find logs -name "*.gz" -mtime +30 -printf "%TY-%Tm-%Td %6s %p\n"
2026-09-03     53 logs/access.log.2.gz
2026-09-08   9000 logs/error.log.3.gz
$ find . -name "*.tmp" -exec ls -l {} +
-rw-r--r-- 1 rajeev rajeev 0 Oct 18 12:08 ./app/cache.tmp
-rw-r--r-- 1 rajeev rajeev 0 Oct 18 12:08 ./app/releases/v1/build.tmp
-rw-r--r-- 1 rajeev rajeev 0 Oct 18 12:08 ./logs/old reports/draft.tmp
$ find . -type f -name "*.tmp" -delete -print
./app/releases/v1/build.tmp
./app/cache.tmp
./logs/old reports/draft.tmp
```

`{} +` packs many files into one command, like `xargs`. `{} \;` runs the command once per file: fine for a
handful, slow for thousands. Names with spaces, like `old reports`, are safe with both, because `find`
passes each name as one argument.

> **Video.** [Linux Crash Course - The find command](https://www.youtube.com/watch?v=skTiK_6DdqU) (Learn Linux TV)

## locate: fast answers from a database

`locate` doesn't search the disk. It searches a list of every file name, built by `updatedb` (on Ubuntu the
package is `plocate`, refreshed by a daily timer). That makes it instant on any size of disk, and it also
means it can be out of date:

```sh
$ locate access.log
$ sudo updatedb
$ locate access.log
/home/rajeev/lab4/logs/access.log
/home/rajeev/lab4/logs/access.log.1
/home/rajeev/lab4/logs/access.log.2.gz
/home/rajeev/lab4/logs/access.log.bak
/home/rajeev/lab4/logs/access.log.bak.gz
/home/rajeev/lab4/logs/access.log.gz
```

The first search found nothing: the files were created after the last `updatedb`. The same happens to a file
made a minute ago:

```sh
$ touch /home/rajeev/lab4/logs/new-today.log
$ locate new-today.log
$ sudo updatedb
$ locate new-today.log
/home/rajeev/lab4/logs/new-today.log
$ locate -c index.html
2
$ locate -b '\index.html'
/home/rajeev/lab4/app/releases/v1/index.html
/home/rajeev/lab4/app/releases/v2/index.html
```

`-c` counts, `-i` ignores case, and `-b '\name'` matches the exact base name instead of any path that contains
it.

|                     | `find`                            | `locate`                                         |
| ------------------- | --------------------------------- | ------------------------------------------------ |
| Searches            | the disk, now                     | a database from the last `updatedb`              |
| Speed on a big disk | slow                              | instant                                          |
| New or deleted file | always right                      | wrong until the next `updatedb`                  |
| Can test            | size, age, owner, permissions     | the name only                                    |
| Use it for          | anything you'll act on, any audit | "where is that config file again?" on a dev host |

Use `locate` to find where something lives. Use `find` before you change or delete anything.

> **Video.** [Quickly Find Any File in Linux with the locate Command](https://www.youtube.com/watch?v=xg9GcuxeRwk) (Learn Linux TV)

## xargs: turning a list into arguments

Many commands take file names as arguments, not as input on stdin. `xargs` bridges the two: it reads a list
and runs a command with the items as arguments. Its classic trap is spaces in names:

```sh
$ find . -name "*.tmp" | xargs rm
rm: cannot remove './logs/old': No such file or directory
rm: cannot remove 'reports/draft.tmp': No such file or directory
$ find . -name "*.tmp" -print0 | xargs -0 rm -v
removed './logs/old reports/draft.tmp'
```

`xargs` split `old reports/draft.tmp` at the space and asked `rm` for two files that don't exist. With
`-print0` and `-0`, names are separated by a null byte, which can't appear in a file name. Use that pair every
time a list of files goes into `xargs`.

```sh
$ printf "web-01\nweb-02\nweb-03\nweb-04\n" | xargs -n 2 echo ping
ping web-01 web-02
ping web-03 web-04
$ printf "" | xargs echo "running with:"
running with:
$ printf "" | xargs -r echo "running with:"
$ find app/releases -name index.html | xargs grep -l v2
app/releases/v2/index.html
$ ls logs/*.log | xargs -I {} cp {} {}.bak
```

| Option  | Does                                                                          |
| ------- | ----------------------------------------------------------------------------- |
| `-0`    | items are separated by null bytes (pair it with `find -print0`)               |
| `-n N`  | at most N items per command                                                   |
| `-r`    | don't run the command at all when the list is empty (GNU runs it once)        |
| `-I {}` | run once per item and put it where `{}` is, even in the middle of the command |
| `-P N`  | run up to N commands at the same time                                         |

Note the empty-input line: without `-r`, `xargs` still ran `echo` once. With `rm -f` or a deploy script,
"ran once with nothing" can do real damage, so add `-r` to anything destructive.

`-P` uses more than one CPU. Compressing four log files one at a time, then four at a time:

```sh
$ time (ls logs/*.log logs/*.bak | xargs -n 1 gzip -k -9)
real	0m0.270s
$ time (ls logs/*.log logs/*.bak | xargs -n 1 -P 4 gzip -k -9)
real	0m0.123s
```

Tiny files, so tiny numbers, but less than half the time. On gigabytes of logs the difference is minutes.

**`find -exec {} +` or `xargs`?** For files, `find -exec … {} +` is simpler and has no splitting trap. Reach
for `xargs` when the list comes from somewhere else (a `grep`, a file, another command) or when you want `-P`.

## Archives: tar, gzip and xz

Sending a release or backup as thousands of separate files is slow and makes permissions and directory layout
easy to lose. An archive packages a tree into one file. `tar` stores the file names and metadata; `gzip` or
`xz` compresses the archive data.

The common flags read like a sequence: `c` creates, `t` lists, `x` extracts, `z` uses gzip, `J` uses xz, and
`f` names the archive file. The `-C` option changes the destination directory before extraction:

```sh
$ tar czf site.tar.gz site/          # c create, z gzip, f file name
$ tar tzf site.tar.gz | head         # t list what's inside, without extracting
$ tar xzf site.tar.gz -C /tmp/restore   # x extract, -C into this folder
$ tar cJf logs.tar.xz /var/log/myapp # J = xz: smaller, slower
$ gzip big.log                       # compress one file → big.log.gz (the original goes)
$ gunzip big.log.gz                  # and back
$ zcat big.log.gz | grep ERROR       # read a compressed file without unpacking it
```

| Format      | Speed  | Size     | Seen as                                   |
| ----------- | ------ | -------- | ----------------------------------------- |
| gzip (`z`)  | fast   | good     | `.tar.gz`, `.tgz`: logs, everyday backups |
| xz (`J`)    | slow   | smallest | `.tar.xz`: release downloads              |
| bzip2 (`j`) | middle | middle   | `.tar.bz2`: older projects                |

Always list an archive (`tar tzf`) before extracting one you didn't make: some archives contain a
folder, others spill files straight into your current directory.

`dd` copies raw bytes, such as a whole disk to an image file. It's powerful and unforgiving:
`dd` to the wrong `of=` device erases it. Use it only when you've double-checked both names.

List an archive before extracting an untrusted or unfamiliar file. Extract into a dedicated empty directory
so you can inspect its contents and avoid overwriting current files. Choose gzip for speed and broad support;
choose xz when a smaller archive matters more than compression time. A common mistake is assuming an archive
is safe because its filename looks familiar.

## Hard links and symlinks

> **Figure.** Hard links and symlinks. A file's data lives in an inode. A file name points at the inode; a hard link is a second name pointing at the same inode, so deleting one name leaves the data. A symlink is a small file that stores a path to another name; delete the target and the symlink breaks.
>
> A hard link is another name for the same data. A symlink is a signpost to a path.

```sh
$ ln data.txt data-hard.txt          # hard link: same inode, same data
$ ln -s /srv/app/releases/v2 current # symlink: a pointer to a path
$ ls -li
1311 -rw-r--r-- 2 rajeev rajeev 12 Oct 13 11:02 data-hard.txt
1311 -rw-r--r-- 2 rajeev rajeev 12 Oct 13 11:02 data.txt
1318 lrwxrwxrwx 1 rajeev rajeev 20 Oct 13 11:03 current -> /srv/app/releases/v2
```

The same inode number (1311) and a link count of 2 show the hard link. The `l` and the `->`
show the symlink.

|                    | Hard link        | Symlink                                        |
| ------------------ | ---------------- | ---------------------------------------------- |
| Points to          | the data (inode) | a path                                         |
| Works across disks | no               | yes                                            |
| Works for folders  | no               | yes                                            |
| Original deleted   | still works      | breaks ("dangling")                            |
| Used for           | rarely, by hand  | config switches, releases, `/etc/alternatives` |

Copying makes an independent duplicate: change the copy, the original stays. Linking gives you
one thing with two names: change it through either, both see the change.

> **In production: releases and a current symlink.** Many deploy tools work like this: each release goes into its own folder, and a symlink called `current` points at the live one. The web server serves `current/`. Deploying is changing the link, rolling back is changing it back, and the old release is still on disk if you need it.

## Mission: Ship a release with a symlink switch

Package version 2 of a small site, unpack it next to version 1, switch the live link to v2 in one step, then roll back to v1. Prove which version is live after each step.

- You need: ~/lab4/site-v2 (a folder with index.html)
- You'll have: ~/lab4/app/current → releases/v1

```sh
$ mkdir -p ~/lab4/app/releases/v1 ~/lab4/site-v2
$ echo "version 1" > ~/lab4/app/releases/v1/index.html
$ echo "version 2" > ~/lab4/site-v2/index.html
$ cd ~/lab4
$ tar czf site-v2.tar.gz -C site-v2 .                 # package v2
$ mkdir app/releases/v2 && tar xzf site-v2.tar.gz -C app/releases/v2
$ ln -sfn releases/v1 app/current && cat app/current/index.html
version 1
$ ln -sfn releases/v2 app/current && cat app/current/index.html   # deploy
version 2
$ ln -sfn releases/v1 app/current && cat app/current/index.html   # roll back
version 1
$ ls -l app/current
lrwxrwxrwx 1 rajeev rajeev 11 Oct 13 11:20 app/current -> releases/v1
```

`-s` makes a symlink, `-f` replaces the existing one, and `-n` treats an existing link to a folder
as the link itself, so `ln` replaces it instead of creating a new link inside the old release.

## Try it

- Create `~/lab4/run.sh`, check its permissions with `ls -l`, then make it executable with `chmod u+x`.
- Set a file to `640` with `chmod`, then read the permissions back in letters.
- Run `umask`, create a file and a folder, and explain their permissions.
- Pack `~/lab4` into `lab4.tar.gz`, list it with `tar tzf`, and extract it into `/tmp/restore`.
- Make a hard link and a symlink to the same file, delete the original, and see which one still works.
- Run `find /usr/bin -perm -4000` and look up what two of the setuid programs do.
- Create a file, search for it with `locate`, run `sudo updatedb`, and search again.

## Quiz

1. A file shows -rw-r-----. Who can read it?
   - Everyone
   - **The owner and members of the file's group** (answer)
   - Only the owner
   Why: rw- is the owner (read, write), r-- the group (read), --- everyone else (nothing). In numbers that's 640.

2. A script fails with "Permission denied" when you run ./deploy.sh, but you can cat it. What's missing?
   - The read bit
   - **The execute bit: chmod u+x deploy.sh** (answer)
   - sudo
   Why: Reading and running are separate permissions. cat needs r; running a file needs x.

3. You can list a folder's files with ls, but cd into it fails. Which bit is missing on the folder?
   - r
   - w
   - **x** (answer)
   Why: On a folder, r lets you list names, w lets you create and delete files inside, and x lets you enter it and reach the files.

4. Your app needs to switch from release v1 to v2 in one instant step, and roll back just as fast. What's the usual approach?
   - Copy the v2 files over the v1 files
   - **Point a symlink called current at the release folder, and flip it with ln -sfn** (answer)
   - Rename the folders with mv while the app runs
   Why: The app always runs from current/. Changing where a symlink points is a single step, and pointing it back is the rollback.

5. You delete the original file. Which link still opens the data?
   - The symlink
   - **The hard link** (answer)
   - Neither
   Why: A hard link is another name for the same inode, so the data stays while any name remains. A symlink stores a path, and that path no longer exists.

6. Why does /tmp have the sticky bit (drwxrwxrwt)?
   - So files there are deleted on reboot
   - **So everyone can create files, but only a file's owner can delete or rename it** (answer)
   - So only root can write there
   Why: Without the sticky bit, write access to a shared folder would let any user delete everyone else's files.

7. You created deploy.log a minute ago. ls shows it, but locate deploy.log prints nothing. Why?
   - **locate searches a database that updatedb refreshes, usually once a day** (answer)
   - locate skips .log files
   - locate only works as root
   Why: locate reads the database from the last updatedb run. Run sudo updatedb, or use find, which searches the disk now.

8. find . -name "*.tmp" | xargs rm fails on the file "old reports/draft.tmp". What fixes it?
   - Run it with sudo
   - Add -n 1 to xargs
   - **find . -name "*.tmp" -print0 | xargs -0 rm, or simply find . -name "*.tmp" -delete** (answer)
   Why: xargs splits its input at spaces, so it asked rm for ./logs/old and reports/draft.tmp. Null-separated names (-print0 with -0) can't be split wrongly.

## Resources

- [chmod(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/chmod.1.html) (Ubuntu manpages)
- [tar(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/tar.1.html) (Ubuntu manpages)
- [ln(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/ln.1.html) (Ubuntu manpages)
- [find(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/find.1.html) (Ubuntu manpages)
- [LPIC-1 exam 101, objectives 103.3, 104.5 and 104.6](https://www.lpi.org/our-certifications/exam-101-objectives/) (Linux Professional Institute)
