๐ Shell Scripting One-Page Manual (Bash)
๐ Basics
Shebang (First Line)
#!/bin/bash
Tells the system to use Bash to run the script.
Run a Script
chmod +x script.sh # Make executable
./script.sh # Run
๐ง Variables
NAME="Alice"
echo "Hello, $NAME"
- No space around
= - Use
$VARto access
๐งฎ Conditionals
if [ "$AGE" -ge 18 ]; then
echo "Adult"
else
echo "Minor"
fi
Comparison operators:
- Strings:
=,!=,-z,-n - Numbers:
-eq,-ne,-lt,-le,-gt,-ge
๐ Loops
For Loop
for i in 1 2 3; do
echo $i
done
While Loop
while [ "$x" -le 5 ]; do
echo $x
((x++))
done
๐ฆ Functions
greet() {
echo "Hello, $1"
}
greet "Bob"
$1,$2, etc. are argumentsreturnoptional; useechofor output
๐ File Tests
if [ -f file.txt ]; then
echo "It's a file"
fi
-f: regular file-d: directory-e: exists-r,-w,-x: read/write/execute
๐ Useful Built-ins
| Command | Purpose |
|---|---|
read VAR |
Read input |
echo |
Print text |
cd, pwd |
Change/print directory |
exit |
Exit script |
source file |
Run a script in current shell |
๐ Tips
- Use
set -eto exit on error - Use
#!/bin/bash -xfor debugging - Quote variables:
"$VAR"to avoid word splitting - Always check
$?for last command status
๐ Bash Shell Scripting Cheat Sheet
๐น BASICS
#!/bin/bash # Shebang
chmod +x script.sh # Make script executable
./script.sh # Run script
๐น VARIABLES
NAME="Alice"
echo "Hello, $NAME"
- No spaces around
= - Use
"$VAR"to prevent word splitting
๐น CONDITIONALS
if [ "$A" -gt 10 ]; then
echo "Greater"
elif [ "$A" -eq 10 ]; then
echo "Equal"
else
echo "Less"
fi
Operators:
| Type | Operators |
|---|---|
| Strings | =, !=, -z, -n |
| Numbers | -eq, -ne, -lt, -le, -gt, -ge |
| Files | -f, -d, -e, -r, -w, -x |
๐น LOOPS
# For Loop
for i in 1 2 3; do echo $i; done
# While Loop
while [ $x -le 5 ]; do echo $x; ((x++)); done
๐น FUNCTIONS
myfunc() {
echo "Arg1 is $1"
}
myfunc "Hello"
๐น INPUT & OUTPUT
read -p "Enter name: " NAME
echo "You typed: $NAME"
๐น SPECIAL VARIABLES
| Symbol | Description |
|---|---|
$0 |
Script name |
$1..$9 |
Arguments |
$# |
Number of arguments |
$@ |
All arguments |
$? |
Exit status of last command |
$$ |
PID of script |
๐น FILE TESTS
[ -f file.txt ] && echo "Regular file"
[ -d dir ] && echo "Directory"
[ -e path ] && echo "Exists"
๐น DEBUGGING & SAFETY
set -e # Exit on error
set -u # Error on undefined variables
set -x # Debug mode (prints commands)