Appendix A: Cheat Sheet of 100 Useful Bash Commands
Introduction to the Command Arsenal
In the vast landscape of Linux command-line operations, having a comprehensive reference guide at your fingertips can mean the difference between swift problem resolution and hours of frustration. This appendix serves as your tactical manual—a carefully curated collection of 100 essential Bash commands that every Linux practitioner should master. Think of this as your digital Swiss Army knife, where each command represents a specialized tool designed for specific tasks in your daily Linux adventures.
The commands presented here are organized by functional categories, ranging from basic file operations to advanced system administration tasks. Each entry includes not only the command syntax but also practical examples and contextual notes that illuminate when and why you might employ each tool. Whether you're a newcomer taking your first steps into the terminal or a seasoned administrator seeking a quick reference, this cheat sheet will serve as your reliable companion.
File and Directory Operations
Basic Navigation and Listing
The foundation of command-line mastery begins with understanding how to navigate and examine your file system. These commands form the bedrock of all other operations.
ls - List Directory Contents
ls -la /home/user
ls --color=auto
ls -lh *.txt
Notes: The -l flag provides detailed information including permissions, ownership, and timestamps. The -a flag reveals hidden files starting with a dot. The -h flag makes file sizes human-readable.
pwd - Print Working Directory
pwd
/home/user/documents/projects
Notes: Essential for orientation within the file system hierarchy. Particularly useful in scripts to determine the current execution context.
cd - Change Directory
cd /var/log
cd ..
cd ~
cd -
Notes: The ~ symbol represents your home directory, .. moves up one level, and - returns to the previous directory.
File and Directory Creation
mkdir - Create Directories
mkdir -p /path/to/nested/directories
mkdir -m 755 new_folder
Notes: The -p flag creates parent directories as needed. The -m flag sets permissions during creation.
touch - Create Empty Files or Update Timestamps
touch newfile.txt
touch -t 202312251200 oldfile.txt
Notes: Beyond creating files, touch can modify access and modification times. The -t flag allows setting specific timestamps.
rmdir - Remove Empty Directories
rmdir empty_folder
rmdir -p path/to/empty/nested/dirs
Notes: Only works on empty directories. Use rm -rf for directories containing files.
File Operations and Manipulation
cp - Copy Files and Directories
cp source.txt destination.txt
cp -r source_dir/ destination_dir/
cp -p file.txt backup/
Notes: The -r flag enables recursive copying for directories. The -p flag preserves file attributes including timestamps and permissions.
mv - Move or Rename Files
mv oldname.txt newname.txt
mv file.txt /new/location/
mv *.log /var/log/archive/
Notes: Unlike cp, mv doesn't create duplicates—it relocates the original file. Can be used for both moving and renaming operations.
rm - Remove Files and Directories
rm file.txt
rm -rf dangerous_directory/
rm -i *.txt
Notes: Exercise extreme caution with -rf flags. The -i flag prompts for confirmation before each deletion, providing a safety net.
Text Processing and Manipulation
Text processing represents one of Linux's greatest strengths, with a rich ecosystem of tools designed for analyzing, transforming, and extracting information from textual data.
File Content Examination
cat - Display File Contents
cat file.txt
cat file1.txt file2.txt > combined.txt
cat -n numbered_file.txt
Notes: Beyond simple display, cat can concatenate multiple files. The -n flag adds line numbers to output.
less - View File Contents with Pagination
less large_file.txt
less +G file.txt # Start at end of file
Notes: Superior to more for file viewing. Supports backward navigation and search functionality using /pattern.
head - Display First Lines of Files
head -n 20 file.txt
head -c 1024 binary_file
Notes: Default shows first 10 lines. The -c flag displays first N bytes instead of lines.
tail - Display Last Lines of Files
tail -n 50 logfile.txt
tail -f /var/log/syslog
tail -F rotating.log
Notes: The -f flag follows file changes in real-time, essential for log monitoring. -F handles file rotation gracefully.
Text Search and Pattern Matching
grep - Search Text Patterns
grep "error" /var/log/syslog
grep -r "TODO" /home/user/projects/
grep -i "warning" *.log
grep -v "debug" application.log
Notes: The -r flag enables recursive directory searching. -i ignores case, -v inverts the match (shows non-matching lines).
egrep - Extended Regular Expression Grep
egrep "(error|warning|critical)" logfile.txt
egrep "^[0-9]{1,3}\.[0-9]{1,3}" network.log
Notes: Supports extended regular expressions without escaping special characters. Equivalent to grep -E.
find - Search for Files and Directories
find /home -name "*.txt" -type f
find . -mtime -7 -size +100M
find /tmp -user john -exec rm {} \;
Notes: Extremely powerful for file system searches. Can execute commands on found files using -exec. Time-based searches use -mtime, -atime, -ctime.
Text Transformation Tools
sed - Stream Editor
sed 's/old/new/g' file.txt
sed -i 's/foo/bar/g' *.txt
sed -n '10,20p' large_file.txt
Notes: The -i flag edits files in-place. The p command prints specific lines. g flag ensures global replacement within each line.
awk - Text Processing Language
awk '{print $1, $3}' data.txt
awk -F: '{print $1}' /etc/passwd
awk 'NR>1 {sum+=$2} END {print sum}' numbers.txt
Notes: Powerful for columnar data processing. -F sets field separator. Built-in variables include NR (record number) and NF (number of fields).
sort - Sort Lines of Text
sort file.txt
sort -n numbers.txt
sort -k2,2 -t: /etc/passwd
sort -u duplicates.txt
Notes: The -n flag performs numeric sorting. -k specifies sort key fields. -u removes duplicate lines.
uniq - Report or Omit Repeated Lines
uniq sorted_file.txt
uniq -c data.txt
uniq -d duplicates.txt
Notes: Requires sorted input to function correctly. -c counts occurrences, -d shows only duplicate lines.
System Information and Process Management
Understanding your system's current state and managing running processes are fundamental skills for effective Linux administration.
System Status Commands
ps - Display Running Processes
ps aux
ps -ef
ps -u username
ps --forest
Notes: aux shows all processes with detailed information. --forest displays process hierarchy. Essential for system monitoring and troubleshooting.
top - Display and Update Sorted Process Information
top
top -u username
top -p 1234,5678
Notes: Interactive process viewer with real-time updates. Press q to quit, k to kill processes, r to renice.
htop - Enhanced Interactive Process Viewer
htop
htop -u username
Notes: More user-friendly than top with color coding and mouse support. May require separate installation on some systems.
df - Display Filesystem Disk Space Usage
df -h
df -i /dev/sda1
df -T
Notes: The -h flag shows human-readable sizes. -i displays inode usage. -T shows filesystem types.
du - Display Directory Space Usage
du -sh /home/user
du -ah --max-depth=1 /var
du -ck *.log
Notes: -s provides summary totals. -a shows all files, not just directories. -c produces a grand total.
Process Control
kill - Terminate Processes
kill 1234
kill -9 stubborn_process_id
kill -HUP daemon_pid
Notes: Default signal is TERM (15). Signal 9 (KILL) forcefully terminates processes. HUP often reloads configuration.
killall - Kill Processes by Name
killall firefox
killall -u username
killall -9 hung_application
Notes: Terminates all processes matching the given name. Use with caution as it affects all instances.
jobs - Display Active Jobs
jobs
jobs -l
Notes: Shows jobs running in the current shell session. -l includes process IDs.
bg - Put Jobs in Background
bg %1
bg
Notes: Continues suspended jobs in the background. Use job numbers from jobs command.
fg - Bring Jobs to Foreground
fg %1
fg
Notes: Brings background jobs to the foreground. Without arguments, affects the most recent job.
nohup - Run Commands Immune to Hangups
nohup long_running_script.sh &
nohup python data_processor.py > output.log 2>&1 &
Notes: Allows processes to continue running after terminal disconnection. Output redirected to nohup.out by default.
Network and Connectivity Commands
Network diagnostics and connectivity testing are essential skills in our interconnected world.
Network Diagnostics
ping - Send ICMP Echo Requests
ping google.com
ping -c 4 192.168.1.1
ping -i 2 -s 1024 target_host
Notes: The -c flag limits packet count. -i sets interval between packets. -s specifies packet size.
wget - Download Files from Web
wget https://example.com/file.zip
wget -r -np -k https://example.com/directory/
wget -c interrupted_download.zip
Notes: The -r flag enables recursive downloading. -c continues partial downloads. -k converts links for offline browsing.
curl - Transfer Data from Servers
curl https://api.example.com/data
curl -X POST -d "param=value" https://api.example.com/
curl -o output.html https://example.com
Notes: More versatile than wget for API interactions. Supports various protocols and HTTP methods.
netstat - Display Network Connections
netstat -tuln
netstat -r
netstat -i
Notes: The -tuln combination shows listening TCP and UDP ports. -r displays routing table. -i shows interface statistics.
ss - Socket Statistics
ss -tuln
ss -p
ss -s
Notes: Modern replacement for netstat. Generally faster and provides more detailed information about socket states.
File Permissions and Ownership
Understanding and managing file permissions forms a crucial aspect of Linux security and system administration.
Permission Management
chmod - Change File Permissions
chmod 755 script.sh
chmod u+x,g-w,o-r file.txt
chmod -R 644 /path/to/directory/
Notes: Numeric notation uses octal values (4=read, 2=write, 1=execute). Symbolic notation uses u/g/o for user/group/other and +/- for add/remove.
chown - Change File Ownership
chown user:group file.txt
chown -R www-data:www-data /var/www/
chown :newgroup file.txt
Notes: Requires appropriate privileges (usually root). The -R flag applies changes recursively. Colon separates user and group.
chgrp - Change Group Ownership
chgrp developers project_files/
chgrp -R staff /shared/documents/
Notes: Specialized command for changing group ownership only. User must be member of the target group.
umask - Set Default File Permissions
umask 022
umask -S
Notes: Sets default permission mask for newly created files. -S displays symbolic representation.
Archive and Compression
Data archiving and compression are essential for backup operations, file distribution, and storage optimization.
Archive Operations
tar - Archive Files
tar -czf archive.tar.gz directory/
tar -xzf archive.tar.gz
tar -tzf archive.tar.gz
tar -czf backup-$(date +%Y%m%d).tar.gz /home/user/
Notes: The c creates archives, x extracts, t lists contents. z adds gzip compression. f specifies filename.
gzip - Compress Files
gzip large_file.txt
gzip -d compressed_file.gz
gzip -9 maximum_compression.txt
Notes: Replaces original file with compressed version. -d decompresses. -9 provides maximum compression.
gunzip - Decompress Gzip Files
gunzip compressed_file.gz
gunzip -t archive.gz
Notes: Equivalent to gzip -d. The -t flag tests archive integrity without extracting.
zip - Create ZIP Archives
zip -r archive.zip directory/
zip -9 maximum.zip file1.txt file2.txt
zip -e encrypted.zip sensitive_data.txt
Notes: The -r flag includes directories recursively. -9 provides maximum compression. -e creates password-protected archives.
unzip - Extract ZIP Archives
unzip archive.zip
unzip -l archive.zip
unzip -d /target/directory/ archive.zip
Notes: The -l flag lists archive contents without extracting. -d specifies extraction directory.
Environment and Variable Management
Environment variables and shell configuration play crucial roles in customizing your Linux experience and controlling program behavior.
Environment Variables
env - Display Environment Variables
env
env -u VARIABLE_NAME command
env VAR=value command
Notes: Without arguments, displays all environment variables. Can run commands with modified environments.
export - Set Environment Variables
export PATH=$PATH:/new/directory
export EDITOR=vim
export -p
Notes: Makes variables available to child processes. -p displays all exported variables.
echo - Display Text and Variables
echo "Hello, World!"
echo $HOME
echo -e "Line 1\nLine 2"
echo -n "No newline"
Notes: The -e flag enables interpretation of backslash escapes. -n suppresses trailing newline.
which - Locate Commands
which python
which -a gcc
Notes: Shows the path of commands that would be executed. -a displays all matching executables in PATH.
whereis - Locate Binary, Source, and Manual Files
whereis ls
whereis -b python
whereis -m gcc
Notes: More comprehensive than which. -b shows binaries only, -m shows manual pages only.
Advanced System Operations
These commands provide powerful capabilities for system administration, monitoring, and troubleshooting complex issues.
System Monitoring
iostat - I/O Statistics
iostat -x 1 5
iostat -d 2
Notes: Part of sysstat package. -x provides extended statistics. Numbers specify interval and count.
vmstat - Virtual Memory Statistics
vmstat 1 10
vmstat -s
vmstat -d
Notes: Displays system activity including memory, processes, and CPU usage. -s shows summary statistics.
free - Display Memory Usage
free -h
free -m -s 5
Notes: The -h flag shows human-readable format. -s enables continuous monitoring with specified interval.
uptime - System Uptime and Load
uptime
uptime -p
uptime -s
Notes: Shows system uptime and load averages. -p displays uptime in pretty format. -s shows boot time.
Advanced File Operations
rsync - Synchronize Files and Directories
rsync -avz source/ destination/
rsync -av --delete local/ remote:/path/
rsync -n -av source/ dest/ # Dry run
Notes: Extremely efficient for backups and synchronization. -a preserves attributes, -v verbose, -z compresses, --delete removes files not in source.
scp - Secure Copy over SSH
scp file.txt user@remote:/path/
scp -r directory/ user@remote:/path/
scp user@remote:/path/file.txt ./
Notes: Copies files securely over SSH. -r enables recursive copying for directories.
ln - Create Links
ln -s /path/to/original /path/to/link
ln original_file hard_link
ln -sf new_target existing_link
Notes: The -s flag creates symbolic links. Hard links share the same inode. -f forces link creation.
Process and Job Management
crontab - Schedule Tasks
crontab -e
crontab -l
crontab -r
Notes: The -e flag edits the crontab file. -l lists current cron jobs. -r removes all cron jobs.
at - Schedule One-time Tasks
at 15:30
at now + 1 hour
at midnight tomorrow
Notes: Interactive scheduler for one-time task execution. Enter commands after running at, then press Ctrl+D.
screen - Terminal Multiplexer
screen -S session_name
screen -ls
screen -r session_name
Notes: Allows multiple terminal sessions within a single connection. -S names sessions, -ls lists sessions, -r reattaches.
tmux - Terminal Multiplexer
tmux new-session -s work
tmux list-sessions
tmux attach-session -t work
Notes: Modern alternative to screen with more features. Supports window splitting and session management.
Text Editors and Configuration
nano - Simple Text Editor
nano filename.txt
nano +25 file.txt # Start at line 25
Notes: User-friendly editor with on-screen help. Ctrl+X to exit, Ctrl+O to save.
vim - Vi Improved Editor
vim filename.txt
vim +/pattern file.txt # Open and search for pattern
Notes: Powerful modal editor. Press i for insert mode, Esc for command mode, :wq to save and quit.
emacs - Extensible Text Editor
emacs filename.txt
emacs -nw file.txt # No GUI mode
Notes: Highly customizable editor. Ctrl+X Ctrl+S to save, Ctrl+X Ctrl+C to exit.
Conclusion: Your Command-Line Mastery Journey
This comprehensive cheat sheet represents more than just a collection of commands—it's your roadmap to Linux proficiency. Each command listed here has been battle-tested in real-world scenarios, from routine system administration tasks to complex troubleshooting situations. The true power of these tools emerges not from memorizing their syntax, but from understanding their interconnected nature and learning to combine them creatively.
As you progress in your Linux journey, you'll discover that mastery comes through practice and experimentation. Start with the basic file operations and gradually incorporate more advanced commands into your daily workflow. Remember that the command line is not just about efficiency—it's about precision, reproducibility, and the ability to automate repetitive tasks.
The beauty of Bash lies in its composability. Commands can be chained together using pipes, redirected to files, and embedded within scripts to create powerful automation solutions. Each command in this cheat sheet serves as a building block in your growing toolkit of Linux expertise.
Keep this reference close at hand, but don't hesitate to explore beyond these 100 commands. The Linux ecosystem offers thousands of specialized tools, each designed to solve specific problems. Use the man command to dive deeper into any tool's capabilities, and remember that the community-driven nature of Linux means help is always available through documentation, forums, and local user groups.
Your journey from command-line novice to expert is not measured in commands memorized, but in problems solved and workflows optimized. Let this cheat sheet be your trusted companion as you navigate the powerful, flexible, and endlessly fascinating world of Linux command-line operations.