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.
Back to SysOpsVariables 8
NAME="value"Define variable (no spaces around =)
echo $NAMERead variable
echo ${NAME}Read variable (recommended, avoids ambiguity)
readonly NAME="value"Define readonly variable
unset NAMEDelete 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 ... fiif statement
if [ -f file ]; then ... fiCheck if file exists
if [ $a -eq $b ]; then ... fiNumeric comparison (-eq -ne -gt -lt)
if [ "$str" = "value" ]; then ... fiString comparison (= !=)
if [[ $str =~ regex ]]; then ... fiRegex match (double brackets)
[ -d dir ] && echo "exists"Short-circuit evaluation
case $var in pattern1) ... ;; pattern2) ... ;; esaccase statement
Loops 6
for i in 1 2 3; do echo $i; donefor loop over a list
for ((i=0; i<10; i++)); do ... doneC-style for loop
while [ condition ]; do ... donewhile loop
until [ condition ]; do ... doneuntil loop (executes while condition is false)
break / continueBreak out of loop / skip iteration
select var in list; do ... doneInteractive selection menu
Functions 7
function name() { ... }Define a function
name() { ... }Define function (shorthand)
name arg1 arg2Call a function
$1 $2 $@Positional parameters / all parameters
$#Number of parameters
return 0Return 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.
Official References
Commands are compiled from the official docs below. Click to verify the latest usage.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us