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
| Command | Description | Example |
|---|---|---|
ls | List directory contents | ls -la (all files with details) |
cd | Change directory | cd /path/to/dir |
pwd | Print working directory | pwd |
mkdir | Create directory | mkdir -p parent/child (with parents) |
rm | Remove files/directories | rm -rf dir (recursive, force) |
cp | Copy files/directories | cp -R source/ dest/ (recursive) |
mv | Move/rename files | mv oldname newname |
touch | Create empty file/update timestamp | touch file.txt |
find | Search for files | find . -name "*.txt" |
locate | Find files by name (using database) | locate filename |
chmod | Change file permissions | chmod 755 script.sh |
chown | Change file owner | chown user:group file |
Text Processing
| Command | Description | Example |
|---|---|---|
cat | Display file contents | cat file.txt |
less | View file with pagination | less large_file.log |
head | Show first lines of file | head -n 10 file.txt |
tail | Show last lines of file | tail -f log.txt (follow updates) |
grep | Search text for patterns | grep -i "error" log.txt (case insensitive) |
sed | Stream editor for text transformation | sed 's/old/new/g' file.txt |
awk | Pattern scanning and processing | awk '{print $1}' file.txt (print first column) |
sort | Sort lines of text | sort -n numbers.txt (numeric sort) |
uniq | Report or filter out repeated lines | sort file.txt | uniq -c (count occurrences) |
wc | Count lines, words, characters | wc -l file.txt (line count) |
cut | Remove sections from lines | cut -d',' -f1,3 data.csv (fields 1 & 3) |
tr | Translate or delete characters | echo "Hello" | tr 'a-z' 'A-Z' (uppercase) |
System Information & Management
| Command | Description | Example |
|---|---|---|
ps | Report process status | ps aux (all processes) |
top | Display running processes | top |
htop | Interactive process viewer | htop |
df | Report disk space usage | df -h (human-readable) |
du | Estimate file space usage | du -sh directory (summary, human-readable) |
free | Display memory usage | free -m (in megabytes) |
uname | Print system information | uname -a (all info) |
hostname | System hostname | hostname |
whoami | Current username | whoami |
uptime | System uptime | uptime |
which | Show full path of commands | which bash |
date | Display or set date/time | date +"%Y-%m-%d" (formatted) |
Network Operations
| Command | Description | Example |
|---|---|---|
ping | Test network connectivity | ping -c 4 google.com (4 packets) |
curl | Transfer data from/to servers | curl -O https://example.com/file.zip (download) |
wget | Non-interactive downloader | wget -q https://example.com/file (quiet) |
ssh | Secure shell client | ssh user@hostname |
scp | Secure copy | scp file.txt user@host:/path/ |
rsync | Fast, versatile file copying | rsync -avz source/ dest/ |
netstat | Network statistics | netstat -tuln (TCP/UDP listening) |
ifconfig | Network interface config | ifconfig eth0 |
ip | IP configuration (modern) | ip addr show |
host | DNS lookup | host example.com |
dig | DNS lookup (detailed) | dig example.com |
nslookup | Query DNS records | nslookup example.com |
File Compression & Archiving
| Command | Description | Example |
|---|---|---|
tar | Tape archive | tar -czvf archive.tar.gz directory/ (create) |
| Â | Â | tar -xzvf archive.tar.gz (extract) |
zip | Create ZIP archive | zip -r archive.zip directory/ |
unzip | Extract ZIP archive | unzip archive.zip |
gzip | Compress files | gzip file.txt |
gunzip | Uncompress gzip files | gunzip file.txt.gz |
Command Chaining & Control Operators
Command Connectors
| Operator | Description | Example |
|---|---|---|
; | Run commands sequentially | cmd1 ; cmd2 (both run regardless) |
&& | Logical AND | cmd1 && cmd2 (cmd2 runs if cmd1 succeeds) |
|| | Logical OR | cmd1 || cmd2 (cmd2 runs if cmd1 fails) |
& | Background execution | cmd & (run in background) |
| | Pipe output to input | cmd1 | cmd2 (cmd1 output to cmd2 input) |
! | Negate a command | ! grep pattern file (true if pattern not found) |
IO Redirection
| Operator | Description | Example |
|---|---|---|
> | Redirect stdout (overwrite) | cmd > file.txt |
>> | Redirect stdout (append) | cmd >> file.txt |
2> | Redirect stderr | cmd 2> errors.log |
2>&1 | Redirect stderr to stdout | cmd > output.txt 2>&1 |
&> | Redirect both stdout and stderr | cmd &> all_output.txt |
< | Input from file | cmd < input.txt |
<< | Here document | cat << EOF ... EOF |
<<< | Here string | grep pattern <<< "string to search" |
/dev/null | Discard output | cmd > /dev/null |
Bash Expansions & Substitutions
Parameter Expansion
| Syntax | Description | Example |
|---|---|---|
${var} | Basic variable expansion | echo ${name} |
${var:-default} | Use default if var unset/null | echo ${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 length | echo ${#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
| Syntax | Description | Example |
|---|---|---|
{x,y,z} | Expand to x y z | echo file.{txt,html,pdf} |
{start..end} | Range expansion | echo {1..5} |
{start..end..step} | Range with step | echo {1..10..2} |
Command Substitution
| Syntax | Description | Example |
|---|---|---|
$(command) | Execute command, substitute output | files=$(ls -la) |
`command` | Legacy syntax for command substitution | today=`date` |
Conditional Expressions
File Test Operators
| Operator | Description | Example |
|---|---|---|
-e file | File exists | [ -e /etc/passwd ] |
-f file | Regular file | [ -f "$script" ] |
-d file | Directory | [ -d "$dir" ] |
-h file | Symbolic link | [ -h "$link" ] |
-r file | Readable | [ -r "$file" ] |
-w file | Writable | [ -w "$file" ] |
-x file | Executable | [ -x "$command" ] |
-s file | Non-zero size | [ -s "$file" ] |
-N file | Modified since last read | [ -N "$file" ] |
file1 -nt file2 | Newer than | [ "$file1" -nt "$file2" ] |
file1 -ot file2 | Older than | [ "$file1" -ot "$file2" ] |
String Test Operators
| Operator | Description | Example |
|---|---|---|
-z string | Empty string | [ -z "$var" ] |
-n string | Non-empty string | [ -n "$var" ] |
str1 = str2 | Equal | [ "$a" = "$b" ] |
str1 != str2 | Not equal | [ "$a" != "$b" ] |
str1 < str2 | Less than (ASCII) | [[ "$a" < "$b" ]] |
str1 > str2 | Greater than (ASCII) | [[ "$a" > "$b" ]] |
=~ | Regex match (in [[]]) | [[ "$email" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$ ]] |
Numeric Comparison Operators
| Operator | Description | Example |
|---|---|---|
-eq | Equal | [ "$a" -eq "$b" ] |
-ne | Not equal | [ "$a" -ne "$b" ] |
-lt | Less than | [ "$a" -lt "$b" ] |
-le | Less than or equal | [ "$a" -le "$b" ] |
-gt | Greater than | [ "$a" -gt "$b" ] |
-ge | Greater than or equal | [ "$a" -ge "$b" ] |
Logical Operators
| Operator | Description | Example |
|---|---|---|
! | Logical NOT | [ ! -f "$file" ] |
-a | Logical AND (in test) | [ "$a" -gt 0 -a "$a" -lt 10 ] |
-o | Logical 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
| Command | Description | Example |
|---|---|---|
echo | Display text | echo "Hello, World!" |
printf | Formatted output | printf "Name: %s\n" "$name" |
read | Read user input | read -p "Enter name: " name |
eval | Execute arguments as command | eval "ls $options" |
source | Execute commands from file | source ~/.bashrc |
. | Same as source | . script.sh |
set | Set/unset shell options | set -e (exit on error) |
unset | Remove variable/function | unset var_name |
export | Set environment variable | export PATH=$PATH:/new/dir |
let | Arithmetic evaluation | let "count = $count + 1" |
declare | Declare variables with attributes | declare -i number=10 (integer) |
readonly | Make variables read-only | readonly API_KEY="abc123" |
shift | Shift positional parameters | shift or shift 2 |
wait | Wait for process completion | wait $pid |
trap | Execute command on signal | trap "echo 'Exiting...'" EXIT |
exec | Replace current process | exec new_command |
exit | Exit with status code | exit 0 |
return | Exit function with status | return 1 |
getopts | Parse command options | while getopts "a:b:" opt; do ... |
Process Management Commands
| Command | Description | Example |
|---|---|---|
jobs | List active jobs | jobs -l (with PID) |
fg | Bring job to foreground | fg %1 (job number 1) |
bg | Resume job in background | bg %2 |
kill | Send signal to process | kill -9 $pid (SIGKILL) |
pkill | Signal processes by name | pkill -f "process_name" |
killall | Kill processes by name | killall httpd |
nohup | Run command immune to hangups | nohup long_process & |
nice | Run with modified priority | nice -n 10 command |
renice | Alter priority of running process | renice +10 -p $pid |
time | Time command execution | time command |
timeout | Run command with time limit | timeout 5s command |
watch | Periodically execute command | watch -n 5 'ls -la' |
crontab | Schedule periodic jobs | crontab -e (edit) |
at | Schedule one-time job | at 10:00 < script.sh |
Advanced Commands & Utilities
| Command | Description | Example |
|---|---|---|
xargs | Build command lines from stdin | find . -name "*.log" | xargs rm |
tee | Read from stdin and write to stdout/files | command | tee output.txt |
bc | Precision calculator | echo "scale=2; 5/2" | bc |
jq | JSON processor | curl api.com/data | jq '.results' |
awk | Pattern scanning and processing | awk -F, '{print $1 " " $3}' file.csv |
sed | Stream editor | sed -i 's/old/new/g' file.txt |
envsubst | Substitute environment variables | envsubst < template.txt > output.txt |
parallel | Execute commands in parallel | ls *.jpg | parallel convert {} {.}.png |
comm | Compare sorted files | comm -12 file1 file2 (common lines) |
diff | Compare files line by line | diff -u file1 file2 |
patch | Apply diff file | patch < patchfile |
split | Split files into pieces | split -b 1G large_file prefix_ |
csplit | Split files by context | csplit file '/^##/' {*} |
join | Join lines on a common field | join file1 file2 |
column | Format output in columns | ls -l | column -t |
fmt | Simple text formatter | fmt -w 80 file.txt |
nl | Number lines | nl -ba file.txt |
seq | Generate sequence of numbers | seq 1 5 |
shuf | Generate random permutations | shuf -n 5 file.txt |
logger | Log to system log | logger "Backup completed" |
Special Variables & Aliases
Helpful Environment Variables
| Variable | Description |
|---|---|
PATH | Executable search path |
HOME | User’s home directory |
USER | Current username |
HOSTNAME | System hostname |
PWD | Current working directory |
OLDPWD | Previous working directory |
SHELL | Path to current shell |
LANG | System language/locale |
TERM | Terminal type |
PS1 | Primary prompt string |
PS2 | Secondary prompt string |
IFS | Internal field separator |
CDPATH | Search path for cd command |
EDITOR | Default 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.
