Bash Scripting — File Existence and Permissions in Scripts
Chapter 18 — File Existence and Permissions in Scripts
Welcome to Chapter 18! 🎉 This is where your scripts start behaving like production-grade tools instead of fragile toys.
Every real-world script touches the filesystem — reading config files, writing logs, creating directories, setting permissions. If your script blindly assumes a file exists or a directory is writable, it will break in production. This chapter teaches you how to write scripts that check first and act safely.
💡 Remember from Part 2? We covered
chmod,chown, and basic file permissions interactively on the command line. Now we’ll use those same concepts inside scripts to automate permission management.
What You’ll Learn
| # | Topic | What You’ll Master |
|---|---|---|
| 1 | File Test Operators | -e, -f, -d, -L, -r, -w, -x, -s, -nt, -ot, -ef |
| 2 | Defensive File Handling | Check-before-open, absolute paths, quoting filenames with spaces |
| 3 | chmod and chown in Scripts | Automate permissions — chmod, chown, stat, EUID checks |
| 4 | Checking for Root Privileges | $EUID vs $UID, root guard patterns, sudo re-execution |
| 5 | Directory Operations in Scripts | mkdir -p, safe cd, pushd/popd, mktemp -d |
| 6 | Practice Exercises | 5 hands-on challenges from easy to advanced |
Prerequisites
Before starting this chapter, make sure you’re comfortable with:
- Chapter 15–17: Variables, conditionals (
if/else), and loops - Part 2 — File Permissions:
chmod,chown,ls -loutput format - Basic test syntax:
[[ condition ]]andifstatements
If any of those feel rusty, take a quick refresher — this chapter builds directly on them.
Why This Matters
Consider this innocent-looking script:
#!/usr/bin/env bash
set -euo pipefail
# ❌ FRAGILE — assumes everything exists
cp /etc/myapp/config.yml /tmp/backup/
chmod 600 /tmp/backup/config.yml
What could go wrong?
/etc/myapp/config.ymlmight not exist →cpfails/tmp/backup/directory might not exist →cpfails- The script might not have read permission on the source
chmodmight fail if the user doesn’t own the file
A defensive version checks all of these before acting. That’s what this chapter teaches.
Quick Reference — File Test Operators
Here’s a cheat sheet you’ll use throughout this chapter:
| Operator | True When… |
|---|---|
-e file |
File exists (any type) |
-f file |
Regular file exists |
-d file |
Directory exists |
-L file |
Symbolic link exists |
-r file |
File is readable |
-w file |
File is writable |
-x file |
File is executable |
-s file |
File exists and is non-empty |
f1 -nt f2 |
File f1 is newer than f2 |
f1 -ot f2 |
File f1 is older than f2 |
f1 -ef f2 |
f1 and f2 are the same inode (hardlinks) |
What’s Next?
Start with File Test Operators → to learn the building blocks, then work through each topic in order. Finish with the Practice Exercises to cement your skills.
Let’s make your scripts bulletproof! 🛡️