Bash Cheat Sheet
Bash Cheat Sheet

This is not just another Bash syntax list. It’s a hands-on, scenario-driven cheat sheet for:
- Running and writing Bash scripts
- Handling variables, arrays, and conditions
- Performing file, directory, and network operations
- Automating routine sysadmin tasks
- Interacting with users and input
- Scheduling with cron
- Mixing Bash with other languages (like Perl)
1. Run a Script
bash myscript.sh # Run directly
chmod +x myscript.sh # Make it executable
./myscript.sh # Then run it
Runs a shell script with or without making it executable.
2. Shebang Basics
#!/usr/bin/bash
Tells the OS which interpreter to use for your script.
3. Hello World + Parameters
echo "Hello $1"
Prints a personalized greeting using the first input argument.
4. Variables and Strings
name="kemal"
echo "${name^^}" # Uppercase
echo "${name,,}" # Lowercase
Store and manipulate text easily in scripts.
5. Arrays
arr=("postgres" "oracle")
arr+=("mysql")
unset arr[1]
Useful for managing lists and collections dynamically.
6. Maps (Associative Arrays)
declare -A db
db[user]="kemal"
echo "${db[user]}"
Key-value storage in Bash scripts.
7. Loops
for i in {1..5}; do echo "Item $i"; done
Repeat tasks without redundancy.
8. Conditions
if [ "$x" -gt 10 ]; then echo "x > 10"; fi
Decision making in scripts.
9. Files & Directories
mkdir -p /tmp/folder
touch /tmp/file.txt
rm -rf /tmp/folder
Automate file system operations.
10. Text Processing
grep "error" logs.txt
sed 's/old/new/g' file.txt
awk '{ print $1 }' file.txt
Search, replace, and parse text content efficiently.
11. Functions
say_hello() { echo "Hi, $1"; }
say_hello Kemal
Reuse logic and simplify your scripts.
12. Argument Checks
if [ -z "$1" ]; then echo "No input"; exit 22; fi
Prevent errors by validating input early.
13. Add a New User (Script Example)
sudo useradd "$1"
Automate user creation on Linux systems.
14. Cron Jobs
crontab -e
Automate script execution at scheduled intervals.
15. File Transfer
scp file.txt user@host:/path/
Move files between machines securely.
16. Package Management
sudo dnf update && sudo dnf upgrade
Keep systems up to date via terminal.
17. Disk Cleanup
du -sh * | sort -h
Analyze and free up space.
18. Network Utilities
ping 8.8.8.8
curl -I https://example.com
Quick checks for connectivity and HTTP responses.
19. Infinite Loop
while true; do echo "Running..."; sleep 1; done
Useful for background or long-running processes.
20. Exit Codes
exit 0 # Success
exit 22 # Custom error
Control script flow and return statuses to other tools.
21. Other Languages
#!/usr/bin/perl
print "Hello from Perl\n";
Run non-Bash scripts using correct interpreters.
← PostgreSQL Blog