Cheat sheet · Tools

Bash scripting cheat sheet

Variables, conditions, loops, functions and safe settings for writing shell scripts that you can trust.
Sections
6
Items
27
Area
Tools
Download
PNG, PDF

Cheat sheet

Bash scripting

Variables, conditions, loops, functions and safe settings for writing shell scripts that you can trust.

/blogs

Script basics

#!/usr/bin/env bash
First line: which program runs the script
chmod +x script.sh && ./script.sh
Make the script runnable, then run it
set -euo pipefail
Stop on errors, unset variables and failed pipes
# comment
A note the shell ignores

Variables

name="Asha"
Set a variable (no spaces around =)
echo "$name"
Use a variable (keep the quotes)
${name:-default}
Use "default" when name is empty or unset
${#name}
Length of the text in name
$(command)
Use the output of a command as a value
export NAME=value
Make a variable visible to other programs

Arguments and results

$1 $2 ...
The first, second ... argument
"$@"
All arguments, each kept separate
$#
How many arguments
$?
Exit code of the last command (0 means success)
exit 1
Stop the script and report a failure

Conditions

if [[ -f file ]]; then ... fi
Run code if the file exists
[[ -d dir ]]
Is it a folder?
[[ -z "$x" ]] / [[ -n "$x" ]]
Is the text empty? / not empty?
[[ $a -eq $b ]] [[ $a == $b ]]
Compare numbers / compare text
cmd1 && cmd2 / cmd1 || cmd2
Run cmd2 only if cmd1 worked / failed

Loops

for f in *.txt; do ...; done
Do something for each matching file
for i in {1..5}; do ...; done
Count from 1 to 5
while read -r line; do ...; done < file
Process a file line by line
while [[ cond ]]; do ...; done
Repeat while the condition is true

Functions

greet() { echo "Hi $1"; }
Define a function
greet Asha
Call it with an argument
local x=1
A variable that lives only inside the function

Remember

  • Always put variables in double quotes: "$file". Unquoted names break on spaces.
  • Run shellcheck on your scripts. It finds most common mistakes for free.

Learn it properly

A cheat sheet helps you remember. These lessons explain the ideas step by step, with examples.

More cheat sheets

All cheat sheets →