Shell Scripting & CLI Tools: From the Command Line to Real Automation
Section 18 of 18
Quick Reference: The Cheat Sheet
Variable Operations at a Glance
var="hello" # Assignment (no spaces!)
echo "$var" # Use variable
echo "${var}" # Safe access (use when ambiguous)
echo "${var:-default}" # Use default if unset (doesn't set var)
echo "${var:=default}" # Set and use default if unset (sets var)
echo "${#var}" # String length
echo "${var^^}" # All uppercase
echo "${var,,}" # All lowercase
echo "${var^}" # Capitalize first letter
echo "${var,}" # Lowercase first letter
echo "${var#prefix}" # Remove shortest prefix
echo "${var##prefix}" # Remove longest prefix (greedy)
echo "${var%suffix}" # Remove shortest suffix
echo "${var%%suffix}" # Remove longest suffix (greedy)
echo "${var/old/new}" # Replace first match
echo "${var//old/new}" # Replace all matches
Test Operators Quick Reference
# Files
[-f, -d, -e, -r, -w, -x, -s, -L # (file, dir, exists, readable, writable, executable, non-empty, symlink)](https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html)
# Strings
-z # empty
-n # non-empty
== # equal
!= # not equal
< # less (lexicographic, inside [[ ]])
> # greater (lexicographic, inside [[ ]])
[=~ # regex match (inside [[ ]])][https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html]
# Numbers (inside [ ] or [[ ]])
-eq # equal
-ne # not equal
-lt # less than
-le # less than or equal
-gt # greater than
-ge # greater than or equal
Common One-Liners
# Find and kill a process by name
[kill $(pgrep process_name)](https://man7.org/linux/man-pages/man1/pgrep.1.html)
# Monitor a command continuously
[watch -n 5 df -h](https://man7.org/linux/man-pages/man1/watch.1.html)
# Show disk usage, sorted
du -sh /* 2>/dev/null | sort -rh | head -20
# Find largest files
find . -type f -exec du -sh {} + | sort -rh | head -10
# Count lines in all Python files
find . -name "*.py" | xargs wc -l | tail -1
# Extract all links from an HTML file
grep -E -o 'href="[^"]+"' page.html | sed 's/href="//' | sed 's/"$//'
# Rename files: replace spaces with underscores
for f in *\ *; do mv "$f" "${f// /_}"; done
# Generate a random password
tr -dc 'a-zA-Z0-9!@#$%' < /dev/urandom | head -c 16; echo
# Watch memory usage live
watch -n 1 'free -h'
# Find files modified in the last 24 hours
find . -type f -mtime -1
[# Find files modified since a specific date (GNU find)
find . -type f -newermt '2024-01-01'](https://man7.org/linux/man-pages/man1/find.1.html)
{% element elem_scenario_17_4_28b1e8 %}
# Tail multiple log files simultaneously
tail -f /var/log/app.log /var/log/nginx/error.log
# Add date prefix to all jpg files in current directory
DATE=$(date +%Y-%m-%d); for f in *.jpg; do mv "$f" "${DATE}_${f}"; done
This cheat sheet will serve you well as a quick reference while you develop your scripting fluency. Pin it somewhere useful.
Now go build something. The terminal is waiting.
Only visible to you
Sign in to take notes.