Linux Basic — File Existence & Permissions
File Existence & Permissions
The fastest way to break a script is to assume a file exists, is readable, is writable, or that you have permission to act on it. Bash gives you a complete set of file test operators that let you verify any of these in one line, plus patterns for handling the failures gracefully.
This chapter turns “it worked on my laptop” into scripts that fail with a clear message — or, better, never fail at all.
What You Will Learn
By the end of this chapter you will be able to:
- Use every common file test operator (
-e,-f,-d,-r,-w,-x,-s,-L,-O,-nt) - Write defensive guards before reading or writing any file
- Apply
chmodandchowncorrectly inside scripts (symbolic vs numeric) - Check whether the current process is root and re-exec with
sudoif not - Create and remove directories safely (idempotent, never
rm -rf $unset/)
Topics in This Chapter
| # | Topic | Description |
|---|---|---|
| 1 | File Test Operators | The full catalogue of [[ -X file ]] tests |
| 2 | Defensive File Handling | Check before you touch |
| 3 | chmod & chown in Scripts | Set permissions and ownership reliably |
| 4 | Checking for Root | $EUID and self-sudo |
| 5 | Directory Operations | mkdir -p, safe deletes, glob patterns |
| 6 | Practice Exercises | Hands-on tasks |
Why “Defensive” Matters
A real-world incident summary you’ve probably seen variations of:
#!/usr/bin/env bash
# Cleanup script
APP_DIR="/var/lib/myapp"
rm -rf "$APP_DIR/cache/" # ← what if APP_DIR is empty?
If a typo upstream left APP_DIR="", that line becomes rm -rf /cache/ — and on the next sysadmin’s machine, possibly rm -rf /. Five extra characters prevent the catastrophe:
[[ -n "$APP_DIR" && -d "$APP_DIR/cache" ]] || { echo "bad APP_DIR" >&2; exit 1; }
rm -rf -- "$APP_DIR/cache/"
That’s defensive scripting in one line: check that the variable is non-empty, that the target directory exists, fail loudly otherwise.
Next → File Test Operators