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

VariableDescription
$0Script name
$1 .. $9Positional 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

OperatorDescription
-z "$str"String is empty
-n "$str"String is not empty
"$a" == "$b"String equality
"$a" != "$b"String inequality
"$a" =~ regexRegex match
-eq, -ne, -lt, -gt, -le, -geInteger comparisons
-f fileFile exists and is regular file
-d dirDirectory exists
-r fileFile is readable
-w fileFile is writable
-x fileFile is executable
-s fileFile 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

SyntaxDescription
${#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

SyntaxDescription
cmd > fileRedirect stdout (overwrite)
cmd >> fileRedirect stdout (append)
cmd 2> fileRedirect stderr
cmd &> fileRedirect stdout and stderr
cmd < fileRead stdin from file
cmd1 | cmd2Pipe stdout to next command
cmd1 |& cmd2Pipe 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