The Ultimate Bash Scripting Commands Cheat Sheet: Essential Command Reference

Introduction

This cheat sheet provides a comprehensive reference for the most useful Bash commands and operators used in shell scripting. Whether you’re writing simple automation scripts or complex system utilities, this guide will help you quickly find the right commands for your Bash scripting needs.

Essential Commands

File System Navigation & Management

CommandDescriptionExample
lsList directory contentsls -la (all files with details)
cdChange directorycd /path/to/dir
pwdPrint working directorypwd
mkdirCreate directorymkdir -p parent/child (with parents)
rmRemove files/directoriesrm -rf dir (recursive, force)
cpCopy files/directoriescp -R source/ dest/ (recursive)
mvMove/rename filesmv oldname newname
touchCreate empty file/update timestamptouch file.txt
findSearch for filesfind . -name "*.txt"
locateFind files by name (using database)locate filename
chmodChange file permissionschmod 755 script.sh
chownChange file ownerchown user:group file

Text Processing

CommandDescriptionExample
catDisplay file contentscat file.txt
lessView file with paginationless large_file.log
headShow first lines of filehead -n 10 file.txt
tailShow last lines of filetail -f log.txt (follow updates)
grepSearch text for patternsgrep -i "error" log.txt (case insensitive)
sedStream editor for text transformationsed 's/old/new/g' file.txt
awkPattern scanning and processingawk '{print $1}' file.txt (print first column)
sortSort lines of textsort -n numbers.txt (numeric sort)
uniqReport or filter out repeated linessort file.txt | uniq -c (count occurrences)
wcCount lines, words, characterswc -l file.txt (line count)
cutRemove sections from linescut -d',' -f1,3 data.csv (fields 1 & 3)
trTranslate or delete charactersecho "Hello" | tr 'a-z' 'A-Z' (uppercase)

System Information & Management

CommandDescriptionExample
psReport process statusps aux (all processes)
topDisplay running processestop
htopInteractive process viewerhtop
dfReport disk space usagedf -h (human-readable)
duEstimate file space usagedu -sh directory (summary, human-readable)
freeDisplay memory usagefree -m (in megabytes)
unamePrint system informationuname -a (all info)
hostnameSystem hostnamehostname
whoamiCurrent usernamewhoami
uptimeSystem uptimeuptime
whichShow full path of commandswhich bash
dateDisplay or set date/timedate +"%Y-%m-%d" (formatted)

Network Operations

CommandDescriptionExample
pingTest network connectivityping -c 4 google.com (4 packets)
curlTransfer data from/to serverscurl -O https://example.com/file.zip (download)
wgetNon-interactive downloaderwget -q https://example.com/file (quiet)
sshSecure shell clientssh user@hostname
scpSecure copyscp file.txt user@host:/path/
rsyncFast, versatile file copyingrsync -avz source/ dest/
netstatNetwork statisticsnetstat -tuln (TCP/UDP listening)
ifconfigNetwork interface configifconfig eth0
ipIP configuration (modern)ip addr show
hostDNS lookuphost example.com
digDNS lookup (detailed)dig example.com
nslookupQuery DNS recordsnslookup example.com

File Compression & Archiving

CommandDescriptionExample
tarTape archivetar -czvf archive.tar.gz directory/ (create)
  tar -xzvf archive.tar.gz (extract)
zipCreate ZIP archivezip -r archive.zip directory/
unzipExtract ZIP archiveunzip archive.zip
gzipCompress filesgzip file.txt
gunzipUncompress gzip filesgunzip file.txt.gz

Command Chaining & Control Operators

Command Connectors

OperatorDescriptionExample
;Run commands sequentiallycmd1 ; cmd2 (both run regardless)
&&Logical ANDcmd1 && cmd2 (cmd2 runs if cmd1 succeeds)
||Logical ORcmd1 || cmd2 (cmd2 runs if cmd1 fails)
&Background executioncmd & (run in background)
|Pipe output to inputcmd1 | cmd2 (cmd1 output to cmd2 input)
!Negate a command! grep pattern file (true if pattern not found)

IO Redirection

OperatorDescriptionExample
>Redirect stdout (overwrite)cmd > file.txt
>>Redirect stdout (append)cmd >> file.txt
2>Redirect stderrcmd 2> errors.log
2>&1Redirect stderr to stdoutcmd > output.txt 2>&1
&>Redirect both stdout and stderrcmd &> all_output.txt
<Input from filecmd < input.txt
<<Here documentcat << EOF ... EOF
<<<Here stringgrep pattern <<< "string to search"
/dev/nullDiscard outputcmd > /dev/null

Bash Expansions & Substitutions

Parameter Expansion

SyntaxDescriptionExample
${var}Basic variable expansionecho ${name}
${var:-default}Use default if var unset/nullecho ${name:-"John"}
${var:=default}Set default if var unset/null${count:=0}
${var:+value}Use value if var set, else nothing${name:+"Hello, $name"}
${var:?error}Error if var unset/null${required:?"Missing value"}
${var:offset}Substring from offset${str:7}
${var:offset:length}Substring with length${str:7:3}
${#var}String lengthecho ${#name}
${var#pattern}Remove shortest match from start${path#*/}
${var##pattern}Remove longest match from start${path##*/}
${var%pattern}Remove shortest match from end${file%.*}
${var%%pattern}Remove longest match from end${file%%.*}
${var/pattern/replacement}Replace first match${text/foo/bar}
${var//pattern/replacement}Replace all matches${text//foo/bar}
${var^}Uppercase first character${name^}
${var^^}Uppercase all characters${name^^}
${var,}Lowercase first character${name,}
${var,,}Lowercase all characters${name,,}

Brace Expansion

SyntaxDescriptionExample
{x,y,z}Expand to x y zecho file.{txt,html,pdf}
{start..end}Range expansionecho {1..5}
{start..end..step}Range with stepecho {1..10..2}

Command Substitution

SyntaxDescriptionExample
$(command)Execute command, substitute outputfiles=$(ls -la)
`command`Legacy syntax for command substitutiontoday=`date`

Conditional Expressions

File Test Operators

OperatorDescriptionExample
-e fileFile exists[ -e /etc/passwd ]
-f fileRegular file[ -f "$script" ]
-d fileDirectory[ -d "$dir" ]
-h fileSymbolic link[ -h "$link" ]
-r fileReadable[ -r "$file" ]
-w fileWritable[ -w "$file" ]
-x fileExecutable[ -x "$command" ]
-s fileNon-zero size[ -s "$file" ]
-N fileModified since last read[ -N "$file" ]
file1 -nt file2Newer than[ "$file1" -nt "$file2" ]
file1 -ot file2Older than[ "$file1" -ot "$file2" ]

String Test Operators

OperatorDescriptionExample
-z stringEmpty string[ -z "$var" ]
-n stringNon-empty string[ -n "$var" ]
str1 = str2Equal[ "$a" = "$b" ]
str1 != str2Not equal[ "$a" != "$b" ]
str1 < str2Less than (ASCII)[[ "$a" < "$b" ]]
str1 > str2Greater than (ASCII)[[ "$a" > "$b" ]]
=~Regex match (in [[]])[[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$ ]]

Numeric Comparison Operators

OperatorDescriptionExample
-eqEqual[ "$a" -eq "$b" ]
-neNot equal[ "$a" -ne "$b" ]
-ltLess than[ "$a" -lt "$b" ]
-leLess than or equal[ "$a" -le "$b" ]
-gtGreater than[ "$a" -gt "$b" ]
-geGreater than or equal[ "$a" -ge "$b" ]

Logical Operators

OperatorDescriptionExample
!Logical NOT[ ! -f "$file" ]
-aLogical AND (in test)[ "$a" -gt 0 -a "$a" -lt 10 ]
-oLogical OR (in test)[ "$a" -lt 0 -o "$a" -gt 100 ]
&&Logical AND (between tests)[ "$a" -gt 0 ] && [ "$a" -lt 10 ]
||Logical OR (between tests)[ "$a" -lt 0 ] || [ "$a" -gt 100 ]

Special Built-in Commands

CommandDescriptionExample
echoDisplay textecho "Hello, World!"
printfFormatted outputprintf "Name: %s\n" "$name"
readRead user inputread -p "Enter name: " name
evalExecute arguments as commandeval "ls $options"
sourceExecute commands from filesource ~/.bashrc
.Same as source. script.sh
setSet/unset shell optionsset -e (exit on error)
unsetRemove variable/functionunset var_name
exportSet environment variableexport PATH=$PATH:/new/dir
letArithmetic evaluationlet "count = $count + 1"
declareDeclare variables with attributesdeclare -i number=10 (integer)
readonlyMake variables read-onlyreadonly API_KEY="abc123"
shiftShift positional parametersshift or shift 2
waitWait for process completionwait $pid
trapExecute command on signaltrap "echo 'Exiting...'" EXIT
execReplace current processexec new_command
exitExit with status codeexit 0
returnExit function with statusreturn 1
getoptsParse command optionswhile getopts "a:b:" opt; do ...

Process Management Commands

CommandDescriptionExample
jobsList active jobsjobs -l (with PID)
fgBring job to foregroundfg %1 (job number 1)
bgResume job in backgroundbg %2
killSend signal to processkill -9 $pid (SIGKILL)
pkillSignal processes by namepkill -f "process_name"
killallKill processes by namekillall httpd
nohupRun command immune to hangupsnohup long_process &
niceRun with modified prioritynice -n 10 command
reniceAlter priority of running processrenice +10 -p $pid
timeTime command executiontime command
timeoutRun command with time limittimeout 5s command
watchPeriodically execute commandwatch -n 5 'ls -la'
crontabSchedule periodic jobscrontab -e (edit)
atSchedule one-time jobat 10:00 < script.sh

Advanced Commands & Utilities

CommandDescriptionExample
xargsBuild command lines from stdinfind . -name "*.log" | xargs rm
teeRead from stdin and write to stdout/filescommand | tee output.txt
bcPrecision calculatorecho "scale=2; 5/2" | bc
jqJSON processorcurl api.com/data | jq '.results'
awkPattern scanning and processingawk -F, '{print $1 " " $3}' file.csv
sedStream editorsed -i 's/old/new/g' file.txt
envsubstSubstitute environment variablesenvsubst < template.txt > output.txt
parallelExecute commands in parallells *.jpg | parallel convert {} {.}.png
commCompare sorted filescomm -12 file1 file2 (common lines)
diffCompare files line by linediff -u file1 file2
patchApply diff filepatch < patchfile
splitSplit files into piecessplit -b 1G large_file prefix_
csplitSplit files by contextcsplit file '/^##/' {*}
joinJoin lines on a common fieldjoin file1 file2
columnFormat output in columnsls -l | column -t
fmtSimple text formatterfmt -w 80 file.txt
nlNumber linesnl -ba file.txt
seqGenerate sequence of numbersseq 1 5
shufGenerate random permutationsshuf -n 5 file.txt
loggerLog to system loglogger "Backup completed"

Special Variables & Aliases

Helpful Environment Variables

VariableDescription
PATHExecutable search path
HOMEUser’s home directory
USERCurrent username
HOSTNAMESystem hostname
PWDCurrent working directory
OLDPWDPrevious working directory
SHELLPath to current shell
LANGSystem language/locale
TERMTerminal type
PS1Primary prompt string
PS2Secondary prompt string
IFSInternal field separator
CDPATHSearch path for cd command
EDITORDefault text editor

Useful Aliases (Add to .bashrc)

# Navigation
alias ll='ls -la'
alias la='ls -a'
alias l='ls -CF'
alias ..='cd ..'
alias ...='cd ../..'

# Safety
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Shortcuts
alias c='clear'
alias h='history'
alias j='jobs -l'

# System info
alias meminfo='free -m -l -t'
alias cpuinfo='lscpu'
alias diskinfo='df -h'

# Network
alias ports='netstat -tulanp'
alias myip='curl http://ipecho.net/plain; echo'

Resources for Further Learning

Official Documentation

  • GNU Bash Reference Manual: https://www.gnu.org/software/bash/manual/
  • Man pages: man bash, man test

Online Resources

  • Bash Guide for Beginners: https://tldp.org/LDP/Bash-Beginners-Guide/html/
  • Explainshell.com (command explanations)
  • ShellCheck (script analysis tool)

This cheat sheet provides a comprehensive reference for Bash scripting commands. Remember that many commands have additional options and functionalities not covered here—check their man pages (man command) for complete documentation.

Scroll to Top