Shell
Bash Cheatsheet
Quick reference for Bash shell scripting including variables, loops, conditionals, string manipulation, and file operations.
Variables
NAME="world" # Assignment (no spaces around =)
echo "Hello $NAME" # Double quotes: variable expansion
echo 'Hello $NAME' # Single quotes: literal string
echo "Path is ${HOME}/bin" # Braces for clarity
readonly PI=3.14 # Read-only variable
unset NAME # Delete variable
export VAR="value" # Export to child processes
Special Variables
| Variable | Description |
|---|
$0 | Script name |
$1 .. $9 | Positional arguments |
$# | Number of arguments |
$@ | All arguments (separate words) |
$* | All arguments (single string) |
$? | Exit status of last command |
$$ | Current process ID |
$! | PID of last background process |
Conditionals
if [[ condition ]]; then
# ...
elif [[ condition ]]; then
# ...
else
# ...
fi
Test Operators
| Operator | Description |
|---|
-z "$str" | String is empty |
-n "$str" | String is not empty |
"$a" == "$b" | String equality |
"$a" != "$b" | String inequality |
"$a" =~ regex | Regex match |
-eq, -ne, -lt, -gt, -le, -ge | Integer comparisons |
-f file | File exists and is regular file |
-d dir | Directory exists |
-r file | File is readable |
-w file | File is writable |
-x file | File is executable |
-s file | File exists and is not empty |
Loops
# For loop
for i in 1 2 3; do echo "$i"; done
# C-style for
for ((i=0; i<10; i++)); do echo "$i"; done
# While loop
while [[ condition ]]; do
# ...
done
# Read lines from file
while IFS= read -r line; do
echo "$line"
done < file.txt
# Iterate over array
arr=(a b c)
for item in "${arr[@]}"; do echo "$item"; done
String Manipulation
| Syntax | Description |
|---|
${#str} | String length |
${str:0:5} | Substring (offset, length) |
${str#pattern} | Remove shortest prefix match |
${str##pattern} | Remove longest prefix match |
${str%pattern} | Remove shortest suffix match |
${str%%pattern} | Remove longest suffix match |
${str/old/new} | Replace first occurrence |
${str//old/new} | Replace all occurrences |
${str,,} | Lowercase |
${str^^} | Uppercase |
${str:-default} | Default if unset/empty |
${str:=default} | Assign default if unset/empty |
Arrays
arr=(one two three) # Declare array
arr+=("four") # Append
echo "${arr[0]}" # Access element
echo "${arr[@]}" # All elements
echo "${#arr[@]}" # Array length
unset arr[1] # Remove element
declare -A map # Associative array
map[key]="value"
echo "${!map[@]}" # All keys
File Operations & Redirection
| Syntax | Description |
|---|
cmd > file | Redirect stdout (overwrite) |
cmd >> file | Redirect stdout (append) |
cmd 2> file | Redirect stderr |
cmd &> file | Redirect stdout and stderr |
cmd < file | Read stdin from file |
cmd1 | cmd2 | Pipe stdout to next command |
cmd1 |& cmd2 | Pipe stdout and stderr |
Functions
greet() {
local name="$1" # Local variable
echo "Hello, $name"
return 0 # Exit status
}
greet "world"
result=$(greet "world") # Capture output
Useful Patterns
# Ternary-like
[[ condition ]] && echo "true" || echo "false"
# Default value
val="${1:-default}"
# Check command exists
command -v git &>/dev/null && echo "git found"
# Here document
cat <<EOF
Hello $NAME
EOF
# Trap signals
trap 'echo "Caught SIGINT"; exit' INT
# Process substitution
diff <(ls dir1) <(ls dir2)
Arithmetic
result=$((5 + 3)) # Arithmetic expansion
((count++)) # Increment
((count += 5)) # Add and assign