Bash Cheatsheet - Shell Scripting Command Reference

Essential Bash scripting syntax on one page. Variables, loops, functions, and string operations — reference directly when writing shell scripts.

SysOps·43 commands·Last updated 2026-07-21
Back to SysOps

Variables 8

NAME="value"
Define variable (no spaces around =)
echo $NAME
Read variable
echo ${NAME}
Read variable (recommended, avoids ambiguity)
readonly NAME="value"
Define readonly variable
unset NAME
Delete variable
${VAR:-default}
Use default value if variable is empty
${VAR:=default}
Assign and use default if variable is empty
${#VAR}
Get string length

Conditionals 7

if [ condition ]; then ... fi
if statement
if [ -f file ]; then ... fi
Check if file exists
if [ $a -eq $b ]; then ... fi
Numeric comparison (-eq -ne -gt -lt)
if [ "$str" = "value" ]; then ... fi
String comparison (= !=)
if [[ $str =~ regex ]]; then ... fi
Regex match (double brackets)
[ -d dir ] && echo "exists"
Short-circuit evaluation
case $var in pattern1) ... ;; pattern2) ... ;; esac
case statement

Loops 6

for i in 1 2 3; do echo $i; done
for loop over a list
for ((i=0; i<10; i++)); do ... done
C-style for loop
while [ condition ]; do ... done
while loop
until [ condition ]; do ... done
until loop (executes while condition is false)
break / continue
Break out of loop / skip iteration
select var in list; do ... done
Interactive selection menu

Functions 7

function name() { ... }
Define a function
name() { ... }
Define function (shorthand)
name arg1 arg2
Call a function
$1 $2 $@
Positional parameters / all parameters
$#
Number of parameters
return 0
Return value (0 means success)
local var="value"
Local variable

String Operations 7

${VAR:offset:length}
Substring extraction
${VAR#pattern}
Remove shortest matching prefix
${VAR##pattern}
Remove longest matching prefix
${VAR%pattern}
Remove shortest matching suffix
${VAR%%pattern}
Remove longest matching suffix
${VAR/pattern/replacement}
Replace first match
${VAR//pattern/replacement}
Replace all matches

File Tests 8

[ -f file ]
File exists and is a regular file
[ -d dir ]
Directory exists
[ -e path ]
Path exists
[ -r file ]
File is readable
[ -w file ]
File is writable
[ -x file ]
File is executable
[ -s file ]
File size is greater than 0
[ file1 -nt file2 ]
file1 is newer than file2

💡 Tips

  • No spaces around = in variable assignment, or it will be interpreted as a command.
  • Always quote variables ("$VAR") to avoid word splitting and special character issues.
  • [ ] is syntactic sugar for the test command; [[ ]] is a Bash extension with more features like regex matching.