Bash Cheat Sheet

Shortcuts & History

Line editing (CTRL)

Line editing (ALT)

Key combos

History

Bash Basics

File Commands

sed (stream editing)

Directory Commands

SSH, System Info & Network Commands

SSH

System & user

Network

Other

Variables

Arrays

array[0]=valA
array=([2]=valC [0]=valA [1]=valB)
array=(valA valB valC)

${array[i]}        # value at index i (index 0 assumed if empty)
${#array[i]}       # length of element i
${#array[@]}       # number of values in array

Parameter expansion (defaults & substrings)

Pattern removal & replacement

Extended glob

Command substitution

Functions

function functname() {
  shell commands
}

Flow Controls

Operators

String tests

File tests

Numeric tests

if / elif / else

if condition; then
  statements
elif condition; then
  statements
else
  statements
fi

for loops

for x in {1..10}; do
  statements
done

for name in list; do
  statements that can use $name
done

for (( init; condition; update )); do
  statements
done

case

case expression in
  pattern1 ) statements ;;
  pattern2 ) statements ;;
esac

select / while / until

select name in list; do
  statements that can use $name
done

while condition; do
  statements
done

until condition; do
  statements
done

Command-Line Processing Cycle

Input/Output Redirection

Process Handling

Tips & Tricks

# alias for a frequently used host
alias gentlenode='ssh [email protected] -p 3404'

# jump to a directory by name (cdable_vars)
shopt -s cdable_vars
export websites="/Users/mac/Documents/websites"
source .bashrc
cd $websites

Debugging Shell Programs

Colors and Backgrounds

\e or \x1B work instead of \033. -e is required with echo to interpret escapes.

# Reset
Color_Off='\033[0m'          # Text Reset

# Regular Colors
Black='\033[0;30m'   Red='\033[0;31m'   Green='\033[0;32m'  Yellow='\033[0;33m'
Blue='\033[0;34m'    Purple='\033[0;35m' Cyan='\033[0;36m'  White='\033[0;97m'

# Bright variants
LGrey='\033[0;37m'   DGrey='\033[0;90m'  LRed='\033[0;91m'  LGreen='\033[0;92m'
LYellow='\033[0;93m' LBlue='\033[0;94m'  LPurple='\033[0;95m' LCyan='\033[0;96m'

# Bold
BBlack='\033[1;30m'  BRed='\033[1;31m'  BGreen='\033[1;32m' BYellow='\033[1;33m'
BBlue='\033[1;34m'   BPurple='\033[1;35m' BCyan='\033[1;36m' BWhite='\033[1;37m'

# Underline
UBlack='\033[4;30m'  URed='\033[4;31m'  UGreen='\033[4;32m' UYellow='\033[4;33m'
UBlue='\033[4;34m'   UPurple='\033[4;35m' UCyan='\033[4;36m' UWhite='\033[4;37m'

# Background
On_Black='\033[40m'  On_Red='\033[41m'  On_Green='\033[42m' On_Yellow='\033[43m'
On_Blue='\033[44m'   On_Purple='\033[45m' On_Cyan='\033[46m' On_White='\033[47m'
# Usage
echo -e "${Green}This is GREEN text${Color_Off} and normal text"
echo -e "${Red}${On_White}This is Red on White background${Color_Off}"
printf "${Red} This is red \n"