Bash Scripting Cheatsheet

Comprehensive reference guide for Bash shell scripting. Search, browse, and learn essential Bash commands, syntax, and best practices for writing robust shell scripts.

Bash Scripting Cheatsheet

Essential Bash scripting commands and syntax

146

Commands

10

Categories

0

Favorites

32

Sections

Start
Script Header
#!/usr/bin/env bashRecommended shebang for portability
#!/bin/bashDirect path shebang
set -euo pipefailStrict mode: exit on error, unset vars, pipe failures

💡 Always use strict mode for safer scripts

Start
Variables
name="John"Define variable (no spaces around =)
echo $nameUse variable
echo "${name}!"Use variable with braces
readonly name="John"Define constant variable
local name="John"Local variable (inside function)
unset nameUnset/delete variable
Start
String Quotes
echo "Hi $name"Double quotes: variables expanded
echo 'Hi $name'Single quotes: literal string
echo "I'm in $(pwd)"Command substitution in string
Start
Conditional Execution
cmd1 && cmd2Run cmd2 if cmd1 succeeds
cmd1 || cmd2Run cmd2 if cmd1 fails
cmd1 ; cmd2Run both commands sequentially
cmd &Run command in background
Variables
Parameter Expansion
${name}Variable value
${name/J/j}Substitution: John → john
${name:0:2}Substring: position 0, length 2
${name::2}Substring: first 2 chars
${name::-1}Substring: remove last char
${#name}Length of variable
Variables
Default Values
${foo:-val}$foo, or val if unset/null
${foo:=val}Set $foo to val if unset/null
${foo:+val}val if $foo is set (not null)
${foo:?message}Error and exit if $foo unset/null

💡 Omit : to only check if unset (not null)

Variables
String Manipulation
${str%suffix}Remove shortest suffix match
${str%%suffix}Remove longest suffix match
${str#prefix}Remove shortest prefix match
${str##prefix}Remove longest prefix match
${str/from/to}Replace first match
${str//from/to}Replace all matches
Variables
Case Manipulation
${str,}Lowercase first character
${str,,}Lowercase all characters
${str^}Uppercase first character
${str^^}Uppercase all characters
Conditionals
If Statement
if [[ condition ]]; thenStart if block
elif [[ condition ]]; thenElse if
elseElse block
fiEnd if block
Conditionals
String Conditions
[[ -z "$str" ]]String is empty
[[ -n "$str" ]]String is not empty
[[ "$a" == "$b" ]]Strings are equal
[[ "$a" != "$b" ]]Strings are not equal
[[ "$a" =~ regex ]]String matches regex
Conditionals
Numeric Conditions
[[ $a -eq $b ]]Equal
[[ $a -ne $b ]]Not equal
[[ $a -lt $b ]]Less than
[[ $a -le $b ]]Less than or equal
[[ $a -gt $b ]]Greater than
[[ $a -ge $b ]]Greater than or equal
Conditionals
File Conditions
[[ -e file ]]File exists
[[ -f file ]]Is a regular file
[[ -d file ]]Is a directory
[[ -r file ]]File is readable
[[ -w file ]]File is writable
[[ -x file ]]File is executable
Loops
For Loop
for i in /etc/rc.*; doLoop over files
for i in {1..5}; doLoop over range
for i in {5..50..5}; doRange with step
for ((i=0; i<10; i++)); doC-style for loop
for i in "${arr[@]}"; doLoop over array
doneEnd loop
Loops
While Loop
while [[ condition ]]; doWhile loop
while true; doInfinite loop
while read -r line; doRead file line by line
done < file.txtRead from file
Loops
Loop Control
breakExit loop
break 2Exit 2 levels of loops
continueSkip to next iteration
Functions
Defining Functions
myfunc() { ... }Define function (preferred)
function myfunc { ... }Define function (alternate)
myfunc "arg1" "arg2"Call function with arguments
Functions
Function Arguments
$#Number of arguments
$*All arguments as single string
$@All arguments as separate strings
$1, $2, ...Individual arguments
$0Script name

💡 Always quote $@ as "$@" to preserve arguments

Functions
Return Values
return 0Return success (0)
return 1Return failure (non-zero)
result=$(myfunc)Capture function output
local var="value"Local variable in function
Arrays
Indexed Arrays
arr=("a" "b" "c")Define array
arr[0]="value"Set element
${arr[0]}Get element
${arr[-1]}Get last element
${arr[@]}All elements
${#arr[@]}Array length
${!arr[@]}All indices
Arrays
Array Operations
arr+=("item")Append element
unset arr[2]Remove element at index
Arrays
Associative Arrays
declare -A dictDeclare associative array
dict[key]="value"Set key-value
${dict[key]}Get value by key
${!dict[@]}All keys
${dict[@]}All values
I/O
Output Redirection
cmd > fileRedirect stdout to file (overwrite)
cmd >> fileRedirect stdout to file (append)
cmd 2> fileRedirect stderr to file
cmd 2>&1Redirect stderr to stdout
cmd &> fileRedirect both stdout and stderr
cmd >/dev/null 2>&1Discard all output
I/O
Input & Pipes
cmd < fileRead stdin from file
cmd <<< "string"Here string
cmd1 | cmd2Pipe stdout to next command
cmd | tee filePipe and save to file
cmd | xargs cmd2Pass output as arguments
I/O
Reading Input
read varRead line into variable
read -r varRead without backslash escaping
read -p "Prompt: " varRead with prompt
read -s varRead silently (for passwords)
read -n 1 varRead single character
Options
Set Options
set -eExit on error (errexit)
set -uError on unset variables (nounset)
set -o pipefailFail on pipe errors
set -xPrint commands before execution (debug)
set +eDisable errexit (+ disables)
Options
Shopt Options
shopt -s nullglobNon-matching globs expand to nothing
shopt -s nocaseglobCase-insensitive globbing
shopt -s dotglobInclude hidden files in globs
shopt -s globstarEnable ** recursive glob
History
History Commands
historyShow command history
!!Repeat last command
!nExecute command number n
!stringExecute last command starting with string
History
History Expansion
!$Last argument of previous command
!*All arguments of previous command
^old^newQuick substitution
History
Brace Expansion
{a,b,c}Expands to: a b c
{1..5}Expands to: 1 2 3 4 5
{1..10..2}Expands to: 1 3 5 7 9
file{1,2,3}.txtExpands to: file1.txt file2.txt file3.txt
Advanced
Special Variables
$?Exit status of last command
$$PID of current shell
$!PID of last background process
$LINENOCurrent line number
$FUNCNAMECurrent function name
Advanced
Traps & Signals
trap 'cmd' EXITRun cmd on script exit
trap 'cmd' ERRRun cmd on error
trap 'cmd' INTRun cmd on Ctrl+C
trap - EXITRemove trap
Advanced
Debugging
bash -x script.shRun with debug output
bash -n script.shCheck syntax only
echo "Debug: $var" >&2Print to stderr
type commandShow command type/location
command -v cmdCheck if command exists

Quick Reference

Shebang

#!/bin/bash

Strict Mode

set -euo pipefail

Variable

name="value"

If Statement

if [[ ]]; then fi