Linux & Terminal · Cheatsheet
Bash Scripting Cheatsheet
Variables, loops, conditionals, functions, and scripting patterns for Bash shell
53 commands 7 sections
No entry matches that filter.
-
NAME="value"Assign variable (no spaces around =) -
$NAME or ${NAME}Reference variable -
"Hello $NAME"String with variable interpolation -
'Hello $NAME'Literal string (no interpolation) -
${#STR}String length -
${STR:0:5}Substring (offset:length) -
${STR/old/new}Replace first occurrence -
${STR//old/new}Replace all occurrences -
${STR^^}Uppercase entire string -
${STR,,}Lowercase entire string
-
if [ condition ]; then ... fiBasic if statement -
if [[ $a == $b ]]; then ...Extended test (preferred) -
-eq -ne -lt -gt -le -geNumeric comparisons -
== !=String comparisons (inside [[ ]]) -
-z "$STR"True if string is empty -
-n "$STR"True if string is non-empty -
-f <file>True if file exists and is regular -
-d <dir>True if directory exists -
-e <path>True if path exists (file or dir) -
&& ||Logical AND / OR
-
for i in 1 2 3; do ... doneFor loop over list -
for i in {1..10}; do ... doneFor loop with range -
for f in *.txt; do ... doneFor loop over files (glob) -
for ((i=0; i<10; i++)); do ...C-style for loop -
while [ condition ]; do ... doneWhile loop -
while read -r line; do ... done < fileRead file line by line -
breakExit loop -
continueSkip to next iteration
-
function name() { ... }Define a function -
name() { ... }Define function (shorthand) -
$1 $2 $3Function arguments (positional) -
$#Number of arguments -
$@All arguments as separate words -
$?Exit status of last command -
return <n>Return exit code from function -
local var="value"Local variable in function
-
echo "text"Print text to stdout -
printf "%s\n" "text"Formatted output -
read -p "Prompt: " VARRead user input into variable -
cmd > fileRedirect stdout to file (overwrite) -
cmd >> fileRedirect stdout to file (append) -
cmd 2> fileRedirect stderr to file -
cmd &> fileRedirect both stdout and stderr -
cmd1 | cmd2Pipe stdout of cmd1 to cmd2 -
cmd < fileRedirect file as stdin
-
$0Script name -
$$Current process ID (PID) -
$!PID of last background process -
$?Exit status of last command -
$_Last argument of previous command -
RANDOMRandom number (0-32767) -
SECONDSSeconds since script started
-
https://www.gnu.org/software/bash/manual/GNU Bash: variables, expansion, conditions, loops, functions, and redirection.