Bash Cheat Sheet
Shortcuts & History
Line editing (CTRL)
CTRL+A — move to beginning of line
CTRL+B — move backward one character
CTRL+C — halt the current command
CTRL+D — delete one character backward or log out (similar to exit)
CTRL+E — move to end of line
CTRL+F — move forward one character
CTRL+G — abort the current editing command and ring the terminal bell
CTRL+H — delete one character under cursor (same as DELETE)
CTRL+J — same as RETURN
CTRL+K — delete (kill) forward to end of line
CTRL+L — clear screen and redisplay the line
CTRL+M — same as RETURN
CTRL+O — same as RETURN, then display the next line in history file
CTRL+P — previous line in command history
CTRL+Q — resume suspended shell output
CTRL+R — search backward through history
CTRL+S — search forward, or suspend shell output
CTRL+T — transpose two characters
CTRL+U — kill backward from point to beginning of line
CTRL+V — make the next character typed verbatim
CTRL+W — kill the word behind the cursor
CTRL+X — list possible filename completions of the current word
CTRL+Y — retrieve (yank) last item killed
CTRL+Z — stop the current command (resume with fg / bg)
Line editing (ALT)
ALT+B — move backward one word
ALT+D — delete next word
ALT+F — move forward one word
ALT+H — delete one character backward
ALT+T — transpose two words
ALT+. — paste last word from the last command (repeats through history)
ALT+U — capitalize every character to the end of the word
ALT+L — uncapitalize every character to the end of the word
ALT+C — capitalize letter under cursor, cursor moves to end of word
ALT+R — revert changes to a command pulled from history
ALT+? — list possible completions of what is typed
ALT+^ — expand line to most recent match from history
Key combos
CTRL+X then (, ), E — record/recall keyboard macro
CTRL+X then CTRL+E — invoke $EDITOR on current command line
CTRL+A then D — log out of screen but keep process running
BACKSPACE — delete character backward
DELETE — delete character under cursor
History
history — show command line history
!! — repeat the last command
!<n> — refer to command line n
!<string> — refer to command starting with string
exit — log out of current session
Bash Basics
env — display all environment variables
echo $SHELL — display the shell you’re using
echo $BASH_VERSION — display bash version
bash — start a new bash shell (type exit to return)
whereis bash — locate the binary, source and manual-page for bash
which bash — find which program is executed as bash
clear — clear the terminal window
File Commands
ls — list files in current directory (ls <dir> for another directory)
ls -l — long format (size, owner, permissions, last modified)
ls -a — all files including hidden (starting with .)
ln -s <filename> <link> — create a symbolic link to a file
readlink <filename> — show where a symbolic link points to
tree — show directories and subdirectories in a file tree
mc — terminal file explorer
touch <filename> — create or update a file
mktemp -t <filename> — make a temp file in /tmp (deleted at next boot; -d for directory)
cat <filename> — display file raw content
cat -n <filename> — show with line numbers
nl <file.sh> — show number of lines
cat f1 > f2 — copy file1 to file2
cat f1 >> f2 — merge two files (append)
more <filename> — page through a file
head <filename> — first 10 lines (head -n 20 file)
tail <filename> — last 10 lines (-f to follow)
vim <filename> — open in VIM (creates it if missing)
mv <file> <dest> — move/rename a file
cp <file> <dest> — copy a file
rm <filename> — remove a file
find . -name <name> <type> — search files by name
diff <f1> <f2> — compare files and show differences
wc <filename> — lines, words, characters (-lwc for one)
sort <filename> — sort text (alphabetical; -n numeric, -r reverse)
sort -t -k <filename> — sort on a specific field (-t separator, -k field)
rev — reverse string characters
chmod -options <filename> — change read/write/execute permissions
gzip <filename> / gunzip <filename> — compress / decompress
gzcat <filename> — view gzipped file without decompressing
grep <pattern> <filenames> — search for a string
grep -r <pattern> <dir> — recursively search a directory
head -n file | tail +n — print nth line from a file
head -y file | tail +x — display lines x through y
sed (stream editing)
sed 's/<p>/<r>/g' <file> — replace pattern with replacement on stdout
sed -i 's/<p>/<r>/g' <file> — replace in place
echo "this" | sed 's/is/at/g' — replace from input stream
Directory Commands
mkdir <dirname> — make a new directory
rmdir <dirname> — remove an empty directory
rmdir -rf <dirname> — remove a non-empty directory
mv <dir1> <dir2> — rename a directory
cd — change to home
cd .. — change to parent directory
cd <dirname> — change directory
cp -r <dir1> <dir2> — copy dir1 into dir2 including sub-directories
pwd — print current directory
cd ~ — change to home
cd - — change to previous working directory
SSH, System Info & Network Commands
SSH
ssh user@host — connect to host as user
ssh -p <port> user@host — connect on a specified port
ssh-copy-id user@host — add your key for passwordless login
System & user
whoami — return your username
su <user> — switch to a different user
su - — switch to root
sudo <command> — execute command as root
passwd — change your password
quota -v — show disk quota
date — current date and time
cal — show month’s calendar
uptime — current uptime
w — display who’s online
finger <user> — info about user
uname -a — kernel information
man <command> — manual for a command
info <command> — alternate documentation system
help — docs about built-ins
df — disk usage
du <filename> — disk usage of files (-s total only)
resize2fs — ext2/ext3/ext4 resizer
last <user> — list last logins
ps -u <user> — list your processes
kill <PID> — kill process by ID
killall <name> — kill all processes by name
top — active processes
lsof — list open files
bg — list/background stopped jobs
fg / fg <job> — bring jobs to foreground
Network
ping <host> — ping host
whois <domain> — whois information
dig <domain> — DNS information
dig -x <host> — reverse lookup
wget <file> — download file
netstat — network connections, routes, interface stats
Other
time <command> — report time consumed by a command
Variables
varname=value — define a variable
varname=value command — variable only in the subprocess environment
echo $varname — check a variable’s value
echo $$ — process ID of current shell
echo $! — process ID of most recent background job
echo $? — exit status of last command
read <varname> — read a string from input into a variable
read -p "prompt" <varname> — read with a prompt
column -t <filename> — pretty columns (often used with pipes)
let <varname> = <equation> — math operations (+, -, *, /, %)
export VARNAME=value — environment variable for subprocesses
export -f <funcname> — export a function
declare -x <varname> — copy Bash variable into environment
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
declare -a — variables treated as arrays
declare -A — associative array
declare -i — variables treated as integers
declare -r — read-only variables
declare -x — marked for export
declare -l — values converted to lowercase
declare -f — use function names only
declare -F — display function names without definitions
Parameter expansion (defaults & substrings)
${varname:-word} — return value, or word if null
${varname:=word} — return value, or set to word if null
${varname:?message} — return value, or abort with message
${varname:+word} — return word if not null, else null
${varname:offset:length} — substring from offset, up to length
${#varname} — length of the value
Pattern removal & replacement
${variable#pattern} — delete shortest match from the beginning
${variable##pattern} — delete longest match from the beginning
${variable%pattern} — delete shortest match from the end
${variable%%pattern} — delete longest match from the end
${variable/pattern/string} — replace first match
${variable//pattern/string} — replace all matches
Extended glob
*(patternlist) — zero or more occurrences
+(patternlist) — one or more occurrences
?(patternlist) — zero or one occurrence
@(patternlist) — exactly one pattern
!(patternlist) — anything except the given patterns
Command substitution
$(UNIX command) — run the command and return its stdout
Functions
function functname() {
shell commands
}
unset -f functname — delete a function definition
declare -f — display all defined functions
- Arguments are passed by position:
$1, $2, … ; $@ = all args, $# = count
Flow Controls
Operators
statement1 && statement2 — AND
statement1 || statement2 — OR
-a / -o — AND / OR inside a test expression
String tests
str1 == str2 / str1 != str2 — match / no match
str1 < str2 / str1 > str2 — alphabetical comparison
-n str1 — not null (length > 0)
-z str1 — null (length 0)
File tests
-a file — file exists
-d file — exists and is a directory
-e file — exists (same as -a)
-f file — exists and is a regular file
-r file — read permission
-s file — exists and is not empty
-w file — write permission
-x file — execute permission
-N file — modified since last read
-O file — you own the file
-G file — group matches yours
file1 -nt file2 — file1 is newer
file1 -ot file2 — file1 is older
Numeric tests
-lt less than · -le less/equal · -eq equal · -ge greater/equal · -gt greater than · -ne not equal
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
- Default lookup order: functions → built-ins → scripts/executables in PATH
command — skip aliases/functions; only built-ins and PATH commands
builtin — only built-in commands
enable — enable/disable shell built-ins
eval — run arguments through the command-line processing again
cmd1|cmd2 — pipe; cmd1’s stdout to cmd2’s stdin
< file — take stdin from file
> file — stdout to file
>> file — stdout to file (append)
>|file — force output even if noclobber is set
n>|file — force output from descriptor n
<> file / n<>file — use file as both stdin/stdout
n>file / n<file / n>>file — redirect descriptor n
n>& / n<& — duplicate descriptors
n>&m / n<&m — copy file descriptor n of m
&>file — stdout and stderr to file
<&- — close stdin
>&- — close stdout
n>&- / n<&- — close descriptor n
cmd | tee <file> — output to both terminal and file (-a append)
Process Handling
myCommand & — run in the background
CTRL+Z — suspend a running job
jobs — list jobs (-l shows PID)
fg — bring a job to the foreground
fg %+ / fg %- — most recent / second most recent job
fg %N / fg %string / fg %?string — job number / command prefix / contains
kill -l — list all signals
kill PID — terminate process
kill -s SIGKILL <pid> — force terminate
kill -15 <pid> — TERM signal
kill %1 — kill job number 1
ps — processes of current shell; ps -a all with a tty
trap cmd sig1 sig2 — run command on signal
trap "" sig1 sig2 — ignore signal
trap - sig1 sig2 — reset signal to default
disown <PID|JID> — remove a process from the job list
wait — wait for all background jobs to finish
sleep <number> — wait N seconds
pv — progress bar for data pipes
yes — answer “yes” to every input prompt
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
bash -n scriptname — syntax check only (set -o noexec in script)
bash -v scriptname — echo commands before running (set -o verbose)
bash -x scriptname — echo after processing (set -o xtrace)
trap 'echo $varname' EXIT — print variables on script exit
trap 'errtrap $LINENO' ERR — run on any non-zero exit
trap dbgtrap DEBUG — run before every statement
trap returntrap RETURN — run when a function/source completes
trap - DEBUG — turn off a trap
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"