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 shebangset -euo pipefailStrict mode: exit on error, unset vars, pipe failures💡 Always use strict mode for safer scripts
Start
Variablesname="John"Define variable (no spaces around =)echo $nameUse variableecho "${name}!"Use variable with bracesreadonly name="John"Define constant variablelocal name="John"Local variable (inside function)unset nameUnset/delete variableStart
String Quotesecho "Hi $name"Double quotes: variables expandedecho 'Hi $name'Single quotes: literal stringecho "I'm in $(pwd)"Command substitution in stringStart
Conditional Executioncmd1 && cmd2Run cmd2 if cmd1 succeedscmd1 || cmd2Run cmd2 if cmd1 failscmd1 ; cmd2Run both commands sequentiallycmd &Run command in backgroundVariables
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 variableVariables
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 matchesVariables
Case Manipulation${str,}Lowercase first character${str,,}Lowercase all characters${str^}Uppercase first character${str^^}Uppercase all charactersConditionals
If Statementif [[ condition ]]; thenStart if blockelif [[ condition ]]; thenElse ifelseElse blockfiEnd if blockConditionals
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 regexConditionals
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 equalConditionals
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 executableLoops
For Loopfor i in /etc/rc.*; doLoop over filesfor i in {1..5}; doLoop over rangefor i in {5..50..5}; doRange with stepfor ((i=0; i<10; i++)); doC-style for loopfor i in "${arr[@]}"; doLoop over arraydoneEnd loopLoops
While Loopwhile [[ condition ]]; doWhile loopwhile true; doInfinite loopwhile read -r line; doRead file line by linedone < file.txtRead from fileLoops
Loop ControlbreakExit loopbreak 2Exit 2 levels of loopscontinueSkip to next iterationFunctions
Defining Functionsmyfunc() { ... }Define function (preferred)function myfunc { ... }Define function (alternate)myfunc "arg1" "arg2"Call function with argumentsFunctions
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 Valuesreturn 0Return success (0)return 1Return failure (non-zero)result=$(myfunc)Capture function outputlocal var="value"Local variable in functionArrays
Indexed Arraysarr=("a" "b" "c")Define arrayarr[0]="value"Set element${arr[0]}Get element${arr[-1]}Get last element${arr[@]}All elements${#arr[@]}Array length${!arr[@]}All indicesArrays
Array Operationsarr+=("item")Append elementunset arr[2]Remove element at indexArrays
Associative Arraysdeclare -A dictDeclare associative arraydict[key]="value"Set key-value${dict[key]}Get value by key${!dict[@]}All keys${dict[@]}All valuesI/O
Output Redirectioncmd > fileRedirect stdout to file (overwrite)cmd >> fileRedirect stdout to file (append)cmd 2> fileRedirect stderr to filecmd 2>&1Redirect stderr to stdoutcmd &> fileRedirect both stdout and stderrcmd >/dev/null 2>&1Discard all outputI/O
Input & Pipescmd < fileRead stdin from filecmd <<< "string"Here stringcmd1 | cmd2Pipe stdout to next commandcmd | tee filePipe and save to filecmd | xargs cmd2Pass output as argumentsI/O
Reading Inputread varRead line into variableread -r varRead without backslash escapingread -p "Prompt: " varRead with promptread -s varRead silently (for passwords)read -n 1 varRead single characterOptions
Set Optionsset -eExit on error (errexit)set -uError on unset variables (nounset)set -o pipefailFail on pipe errorsset -xPrint commands before execution (debug)set +eDisable errexit (+ disables)Options
Shopt Optionsshopt -s nullglobNon-matching globs expand to nothingshopt -s nocaseglobCase-insensitive globbingshopt -s dotglobInclude hidden files in globsshopt -s globstarEnable ** recursive globHistory
History CommandshistoryShow command history!!Repeat last command!nExecute command number n!stringExecute last command starting with stringHistory
History Expansion!$Last argument of previous command!*All arguments of previous command^old^newQuick substitutionHistory
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 9file{1,2,3}.txtExpands to: file1.txt file2.txt file3.txtAdvanced
Special Variables$?Exit status of last command$$PID of current shell$!PID of last background process$LINENOCurrent line number$FUNCNAMECurrent function nameAdvanced
Traps & Signalstrap 'cmd' EXITRun cmd on script exittrap 'cmd' ERRRun cmd on errortrap 'cmd' INTRun cmd on Ctrl+Ctrap - EXITRemove trapAdvanced
Debuggingbash -x script.shRun with debug outputbash -n script.shCheck syntax onlyecho "Debug: $var" >&2Print to stderrtype commandShow command type/locationcommand -v cmdCheck if command existsQuick Reference
Shebang
#!/bin/bash
Strict Mode
set -euo pipefail
Variable
name="value"
If Statement
if [[ ]]; then fi