Skip to main content

Bash Cheatsheet

By Dejan Panovski Updated on Download PDF

Quick reference for Bash shell scripting

Bash (Bourne Again Shell) is the default shell on most Linux distributions. This cheatsheet covers essential Bash scripting concepts including variables, conditionals, loops, functions, and more. Perfect for writing automation scripts and working efficiently on the command line.

Script Basics

Start every Bash script with these fundamentals.

SyntaxDescription
#!/bin/bashShebang (script interpreter)
#!/usr/bin/env bashPortable shebang
# commentSingle line comment
chmod +x script.shMake executable
./script.shRun script
source script.shRun in current shell
. script.shSame as source

Variables

Declare and use variables.

SyntaxDescription
var="value"Assign variable (no spaces!)
$varUse variable
${var}Use variable (explicit)
readonly varMake read-only
unset varDelete variable
export varExport to environment
envList environment vars

Special Variables

Built-in variables with special meanings.

VariableDescription
$0Script name
$1 - $9Positional parameters
${10}10th+ parameter
$#Number of arguments
$@All arguments (separate)
$*All arguments (single)
$?Last exit status
$$Current PID
$!Last background PID

Quoting

Control variable expansion and special characters.

SyntaxDescription
"$var"Double quotes (expands vars)
'$var'Single quotes (literal)
\$Escape special char
`cmd`Command substitution (old)
$(cmd)Command substitution
$((expr))Arithmetic expansion

String Operations

Manipulate strings with parameter expansion.

SyntaxDescription
${#var}String length
${var:0:5}Substring (pos 0, len 5)
${var#pattern}Remove prefix (shortest)
${var##pattern}Remove prefix (longest)
${var%pattern}Remove suffix (shortest)
${var%%pattern}Remove suffix (longest)
${var/old/new}Replace first
${var//old/new}Replace all

String Concatenation

Combine strings together.

SyntaxDescription
$a$bConcatenate variables
"${a}${b}"Safe concatenation
"$a and $b"With literal text
var+="more"Append to variable

Default Values

Provide fallback values for variables.

SyntaxDescription
${var:-default}Use default if unset
${var:=default}Set default if unset
${var:+value}Use value if set
${var:?error}Error if unset

Arrays

Work with indexed arrays.

SyntaxDescription
arr=(a b c)Declare array
arr[0]="value"Set element
${arr[0]}Get element
${arr[@]}All elements
${#arr[@]}Array length
${!arr[@]}All indices
arr+=(d e)Append elements
unset arr[1]Delete element

Arithmetic

Perform math operations.

SyntaxDescription
$((a + b))Addition
$((a - b))Subtraction
$((a * b))Multiplication
$((a / b))Division
$((a % b))Modulo
$((a ** b))Exponent
((i++))Increment
((i--))Decrement
((i += 5))Add and assign

Conditionals

Test conditions and make decisions.

SyntaxDescription
if [[ cond ]]; thenIf statement
elif [[ cond ]]; thenElse if
elseElse clause
fiEnd if
[[ cond ]] && cmdShort-circuit and
[[ cond ]] || cmdShort-circuit or

Test Command

The [[ ]] test syntax (preferred over [ ]).

SyntaxDescription
[[ -z $str ]]String is empty
[[ -n $str ]]String not empty
[[ $a == $b ]]Strings equal
[[ $a != $b ]]Strings not equal
[[ $a =~ regex ]]Regex match
[[ $a == *pattern* ]]Glob pattern match

Numeric Comparisons

Compare numbers in conditions.

SyntaxDescription
[[ $a -eq $b ]]Equal
[[ $a -ne $b ]]Not equal
[[ $a -lt $b ]]Less than
[[ $a -le $b ]]Less or equal
[[ $a -gt $b ]]Greater than
[[ $a -ge $b ]]Greater or equal
(( a == b ))Equal (arithmetic)
(( a < b ))Less than (arithmetic)

File Tests

Test file properties.

SyntaxDescription
[[ -e $f ]]File exists
[[ -f $f ]]Is regular file
[[ -d $f ]]Is directory
[[ -L $f ]]Is symlink
[[ -r $f ]]Is readable
[[ -w $f ]]Is writable
[[ -x $f ]]Is executable
[[ -s $f ]]Size > 0
[[ $a -nt $b ]]a newer than b

Logical Operators

Combine multiple conditions.

SyntaxDescription
[[ cond1 && cond2 ]]AND
[[ cond1 || cond2 ]]OR
[[ ! cond ]]NOT
[[ (cond1) ]]Grouping

Case Statement

Pattern matching with multiple branches.

SyntaxDescription
case $var inStart case
pattern)Match pattern
a|b)Match a or b
*)Default case
;;End pattern block
esacEnd case

For Loop

Iterate over lists and ranges.

SyntaxDescription
for i in 1 2 3; doLoop over list
for i in "${arr[@]}"; doLoop over array
for i in *.txt; doLoop over files
for i in {1..10}; doLoop over range
for ((i=0; i<10; i++)); doC-style for
doneEnd loop

While & Until Loops

Loop while/until condition is true.

SyntaxDescription
while [[ cond ]]; doWhile loop
until [[ cond ]]; doUntil loop
while read -r line; doRead file lines
while :; doInfinite loop
doneEnd loop
done < fileRead from file

Loop Control

Control loop execution flow.

SyntaxDescription
breakExit loop
break 2Exit 2 levels
continueSkip to next iteration
continue 2Skip 2 levels

Functions

Define reusable code blocks.

SyntaxDescription
func() { }Define function
function func { }Alternative syntax
func arg1 arg2Call function
$1, $2Function arguments
local var="val"Local variable
return 0Return exit code
result=$(func)Capture output

Input/Output

Read input and display output.

SyntaxDescription
echo "text"Print with newline
echo -n "text"Print without newline
echo -e "a\tb"Enable escapes
printf "%s\n" "$var"Formatted output
read varRead into variable
read -p "prompt: " varRead with prompt
read -s varRead silently
read -r varRaw input (no escapes)

Redirection

Redirect input and output streams.

SyntaxDescription
cmd > fileRedirect stdout
cmd >> fileAppend stdout
cmd 2> fileRedirect stderr
cmd 2>&1Stderr to stdout
cmd &> fileBoth to file
cmd < fileRedirect stdin
cmd1 | cmd2Pipe stdout

Here Documents

Embed multi-line text in scripts.

SyntaxDescription
cat <<EOFHere document
cat <<'EOF'No expansion
cat <<-EOFStrip leading tabs
cmd <<< "string"Here string

Exit Codes

Handle command success and failure.

SyntaxDescription
exit 0Exit success
exit 1Exit failure
$?Last exit code
cmd && echo okRun if success
cmd || echo failRun if failure
set -eExit on error

Select Menu

Create interactive menus.

SyntaxDescription
select opt in a b c; doCreate menu
$optSelected option
$REPLYUser’s input
breakExit menu
doneEnd select

Process Handling

Manage background processes.

SyntaxDescription
cmd &Run in background
waitWait for all jobs
wait $pidWait for PID
$!Last background PID
jobsList jobs
fg %1Bring to foreground

Debugging

Debug and trace script execution.

SyntaxDescription
bash -x script.shTrace execution
set -xEnable tracing
set +xDisable tracing
set -vPrint input lines
set -eExit on error
set -uError on unset vars
set -o pipefailPipe error status

Useful Patterns

Common scripting patterns.

SyntaxDescription
${var:-$(cmd)}Default from command
[[ -f $f ]] && source $fSource if exists
while IFS= read -r lineRead lines safely
"${arr[@]}"Safe array expansion
set -- "$@" newargAppend to args

Configuration Files

Bash startup files.

FileDescription
~/.bashrcInteractive non-login
~/.bash_profileLogin shell
~/.profileGeneric login
~/.bash_aliasesAlias definitions
/etc/bash.bashrcSystem-wide
/etc/profileSystem login