Linux logoLinuxBEGINNER

Linux Essential Commands

Linux commands cheat sheet for file operations, permissions, process management, networking, and shell scripting with syntax examples.

6 min read
linuxbashshellterminalclicommandsunixcommand-line
Loading your progress

File & Directory Operations

ls - List Files

List directory contents with various formatting options

bash
# List files
ls
ls -l          # Long format with details
ls -la         # Include hidden files
ls -lh         # Human-readable sizes (KB, MB, GB)
ls -lt         # Sort by modification time
ls -lS         # Sort by file size
ls -R          # Recursive - show subdirectories
✅ -l shows permissions, owner, size, and modification date
💡 -a includes hidden files (starting with .)
🔍 Combine flags: -lah for detailed, human-readable, with hidden files
filesdirectorylistbasic

Navigate between directories in the filesystem

bash
# Change directory
cd /path/to/directory
cd ~           # Home directory
cd ..          # Parent directory
cd -           # Previous directory
cd             # Home directory (shortcut)
✅ Use tab completion to avoid typing full paths
💡 cd - is useful for toggling between two directories
🔍 pwd shows your current directory path
directorynavigationbasic

cp - Copy Files

Copy files and directories with options for recursive and interactive copying

bash
# Copy files
cp source.txt destination.txt
cp file1.txt file2.txt /target/dir/

# Copy directories (recursive)
cp -r source_dir/ dest_dir/

# Copy with confirmation
cp -i source.txt dest.txt

# Preserve attributes
cp -p file.txt backup.txt
✅ -r (recursive) is required for copying directories
💡 -i prompts before overwriting existing files
🔍 -p preserves timestamps, ownership, and permissions
filescopybasic

Move or rename files and directories

bash
# Move files
mv source.txt /path/to/destination/

# Rename files
mv oldname.txt newname.txt

# Move multiple files
mv file1.txt file2.txt /target/dir/

# Move with confirmation
mv -i source.txt dest.txt
✅ Works for both moving and renaming files
💡 -i prompts before overwriting files
🔍 No -r needed for directories (unlike cp)
filesmoverenamebasic

Delete files and directories (use with caution)

bash
# Remove files
rm file.txt
rm file1.txt file2.txt

# Remove directories
rm -r directory/
rm -rf directory/      # Force remove (no confirmation)

# Remove with confirmation
rm -i file.txt

# Remove empty directory
rmdir empty_dir/
✅ -r (recursive) required for directories
💡 -f forces deletion without prompts (dangerous!)
🔍 Use rm -i to confirm before deleting important files
filesdeleteremovebasic

Create new directories with support for nested paths

bash
# Create directory
mkdir new_directory

# Create nested directories
mkdir -p path/to/nested/directory

# Create multiple directories
mkdir dir1 dir2 dir3

# Create with permissions
mkdir -m 755 directory
✅ -p creates parent directories as needed
💡 -m sets permissions when creating directory
🔍 Use -p to avoid errors if directory already exists
directorycreatebasic

Create empty files or update timestamps

bash
# Create empty file
touch newfile.txt

# Create multiple files
touch file1.txt file2.txt file3.txt

# Update timestamp only
touch existing_file.txt
✅ Creates file if it does not exist
💡 Updates access and modification times on existing files
🔍 Useful for creating placeholder files quickly
filescreatebasic

File Viewing & Editing

Display file contents, concatenate files, or create new files

bash
# Display file contents
cat file.txt

# Display multiple files
cat file1.txt file2.txt

# Display with line numbers
cat -n file.txt

# Create file with content
cat > newfile.txt
(type content, then Ctrl+D to save)
✅ Best for viewing small files
💡 -n adds line numbers to output
🔍 Use less or more for large files
filesviewdisplay

View files one screen at a time with navigation

bash
# View file with pagination
less file.txt

# Navigation:
# Space - Next page
# b - Previous page
# / - Search forward
# ? - Search backward
# n - Next search result
# q - Quit
✅ More efficient than cat for large files
💡 Allows forward and backward navigation
🔍 Search with / and navigate results with n/N
filesviewpagination

View the beginning or end of files

bash
# View first 10 lines
head file.txt

# View first N lines
head -n 20 file.txt

# View last 10 lines
tail file.txt

# View last N lines
tail -n 30 file.txt

# Follow file updates (logs)
tail -f /var/log/syslog
✅ head shows beginning of file, tail shows end
💡 tail -f follows file updates in real-time
🔍 Perfect for monitoring log files as they grow
filesviewlogs

User-friendly terminal text editor for beginners

bash
# Edit file
nano file.txt

# Key shortcuts:
# Ctrl+O - Save file
# Ctrl+X - Exit
# Ctrl+K - Cut line
# Ctrl+U - Paste line
# Ctrl+W - Search
# Ctrl+G - Help
✅ Easiest terminal editor for beginners
💡 Shows keyboard shortcuts at bottom of screen
🔍 Use Ctrl+O to save and Ctrl+X to exit
editortextbeginner

Powerful modal text editor with steep learning curve

bash
# Edit file
vim file.txt

# Basic commands:
# i - Enter insert mode
# Esc - Exit insert mode
# :w - Save
# :q - Quit
# :wq - Save and quit
# :q! - Quit without saving
# dd - Delete line
# yy - Copy line
# p - Paste
✅ Extremely powerful once learned
💡 Press i to start editing, Esc to exit insert mode
🔍 Type :q! to exit without saving changes
⚡ vimtutor command provides interactive tutorial
editortextadvanced

File Permissions & Ownership

Modify file and directory access permissions

bash
# Numeric mode
chmod 755 file.sh      # rwxr-xr-x
chmod 644 file.txt     # rw-r--r--
chmod 600 private.key  # rw-------

# Symbolic mode
chmod u+x script.sh    # Add execute for user
chmod g-w file.txt     # Remove write for group
chmod o+r file.txt     # Add read for others
chmod a+x file.sh      # Add execute for all

# Recursive
chmod -R 755 directory/
✅ 755 = rwxr-xr-x (common for scripts and directories)
💡 644 = rw-r--r-- (common for regular files)
🔍 First digit=user, second=group, third=others
⚡ r=4, w=2, x=1 (add numbers for combinations)
permissionssecuritychmod

Change file owner and group

bash
# Change owner
sudo chown username file.txt

# Change owner and group
sudo chown username:groupname file.txt

# Change only group
sudo chown :groupname file.txt

# Recursive
sudo chown -R username:groupname directory/
✅ Requires sudo for files you do not own
💡 Use colon (:) to specify group
🔍 -R changes ownership recursively in directories
ownershippermissionssudo

Change group ownership of files

bash
# Change group
chgrp groupname file.txt

# Recursive
chgrp -R groupname directory/

# View current groups
groups
id
✅ Changes only group ownership (not user)
💡 Use groups command to see available groups
🔍 Alternative to chown for group-only changes
grouppermissionsownership

Process Management

Display currently running processes

bash
# View all processes
ps aux

# View user processes
ps -u username

# View process tree
ps auxf

# Find specific process
ps aux | grep process_name
✅ ps aux shows all running processes with details
💡 Use grep to filter for specific processes
🔍 PID (Process ID) is in the second column
processesmonitoringsystem

Real-time view of system processes and resource usage

bash
# Launch top
top

# Common keys:
# q - Quit
# k - Kill process (prompts for PID)
# M - Sort by memory usage
# P - Sort by CPU usage
# h - Help
✅ Updates every few seconds showing CPU and memory usage
💡 Press M to sort by memory, P to sort by CPU
🔍 Press k then enter PID to kill a process
processesmonitoringinteractive

Send signals to processes to stop them

bash
# Kill by PID
kill 1234

# Force kill
kill -9 1234

# Kill by name
killall process_name
pkill process_name

# List signals
kill -l
✅ kill sends SIGTERM (graceful shutdown) by default
💡 -9 sends SIGKILL (force kill, no cleanup)
🔍 Use ps aux | grep to find process PIDs
⚡ killall affects all processes with that name
processeskillterminate

Background Jobs

Run processes in background and manage jobs

bash
# Run in background
command &

# Background current process
Ctrl+Z
bg

# List jobs
jobs

# Bring to foreground
fg %1

# Keep running after logout
nohup command &
✅ & runs command in background immediately
💡 Ctrl+Z suspends current process, bg resumes it in background
🔍 jobs shows all background jobs with IDs
⚡ nohup keeps process running after logout
jobsbackgroundprocesses

System Information

System Overview

Display system information and kernel details

bash
# System info
uname -a       # All info
uname -r       # Kernel version
uname -m       # Architecture

# OS info
cat /etc/os-release
lsb_release -a

# Hostname
hostname
✅ uname -a shows kernel, hostname, and architecture
💡 /etc/os-release contains distribution details
🔍 Use uname -r to check kernel version for driver compatibility
systeminfokernel

Disk Usage

Check disk space and directory sizes

bash
# Disk space by filesystem
df -h

# Directory sizes
du -h directory/
du -sh directory/      # Summary only
du -h --max-depth=1    # One level deep

# Largest files/dirs
du -ah | sort -rh | head -20
✅ df -h shows available space on all mounted filesystems
💡 du -sh gives total size of a directory
🔍 -h makes sizes human-readable (GB, MB, KB)
diskstoragespace

Memory Usage

View RAM and swap memory usage

bash
# Memory info
free -h

# Detailed memory info
cat /proc/meminfo

# Memory by process
top
ps aux --sort=-%mem | head
✅ free -h shows total, used, and available RAM
💡 -h displays in human-readable format
🔍 Check available column for actual free memory
memoryramsystem

Check how long system has been running and load average

bash
# Uptime and load
uptime

# Who is logged in
who
w

# Current user
whoami
id
✅ uptime shows time running and load averages
💡 Load averages: 1min, 5min, 15min intervals
🔍 whoami shows current username
uptimeloadusers

Networking

Check network connectivity to a host

bash
# Ping host
ping google.com

# Ping with count
ping -c 4 google.com

# Ping with interval
ping -i 2 google.com
✅ Tests if host is reachable and measures latency
💡 -c limits number of pings (useful in scripts)
🔍 Press Ctrl+C to stop continuous ping
networkconnectivityping

Make HTTP requests and download files from command line

bash
# GET request
curl https://api.example.com

# Save to file
curl -o output.html https://example.com
curl -O https://example.com/file.zip

# Follow redirects
curl -L https://example.com

# POST data
curl -X POST -d "key=value" https://api.example.com
✅ -O saves file with original name, -o specifies name
💡 -L follows redirects (important for many URLs)
🔍 Use -I to see headers only
networkhttpdownloadcurl

Download files from the web with resume capability

bash
# Download file
wget https://example.com/file.zip

# Continue interrupted download
wget -c https://example.com/large-file.iso

# Download quietly
wget -q https://example.com/file.zip

# Mirror website
wget -m https://example.com
✅ Better than curl for downloading large files
💡 -c resumes interrupted downloads
🔍 Automatically retries failed downloads
networkdownloadwget

Securely connect to remote servers

bash
# Connect to server
ssh username@hostname

# Connect with port
ssh -p 2222 username@hostname

# Execute command
ssh username@hostname 'ls -la'

# SSH with key
ssh -i ~/.ssh/key.pem username@hostname
✅ Secure encrypted connection to remote machines
💡 -i specifies private key file for authentication
🔍 Store keys in ~/.ssh/ directory (chmod 600)
networksshremotesecurity

Copy files between local and remote machines via SSH

bash
# Copy to remote
scp file.txt username@hostname:/path/to/destination/

# Copy from remote
scp username@hostname:/path/to/file.txt ./

# Copy directory
scp -r directory/ username@hostname:/path/

# With custom port
scp -P 2222 file.txt username@hostname:/path/
✅ Uses SSH for secure file transfer
💡 -r copies directories recursively
🔍 -P (uppercase) specifies port for scp
networkscpcopyremote

View network interfaces, connections, and routing

bash
# IP address
ip addr
ip a

# Network statistics
netstat -tuln      # Listening ports
netstat -ant       # All connections

# Modern alternative
ss -tuln           # Listening ports
ss -ant            # All connections
✅ ip addr shows all network interfaces and IPs
💡 ss is faster and more modern than netstat
🔍 -tuln shows TCP/UDP listening ports with numbers
networkipnetstatconnections

Search & Find

Search for files and directories by name, type, size, and more

bash
# Find by name
find /path -name "filename.txt"
find . -name "*.js"

# Find by type
find . -type f         # Files only
find . -type d         # Directories only

# Find by size
find . -size +100M     # Larger than 100MB
find . -size -1M       # Smaller than 1MB

# Find and execute
find . -name "*.log" -delete
find . -type f -exec chmod 644 {} \;
✅ -name searches by filename (case-sensitive)
💡 Use -iname for case-insensitive search
🔍 -exec runs commands on found files
⚡ . searches current directory and subdirectories
searchfindfiles

Search for patterns in file contents

bash
# Search in file
grep "pattern" file.txt

# Case-insensitive
grep -i "pattern" file.txt

# Recursive search
grep -r "pattern" directory/

# Show line numbers
grep -n "pattern" file.txt

# Count matches
grep -c "pattern" file.txt

# Invert match (exclude)
grep -v "pattern" file.txt
✅ -i ignores case, -r searches recursively
💡 -n shows line numbers for matches
🔍 Use grep with pipes: ps aux | grep process_name
searchgreppatterntext

Quickly find files by name using pre-built database

bash
# Search for file
locate filename.txt

# Case-insensitive
locate -i filename.txt

# Update database
sudo updatedb

# Limit results
locate -n 10 filename.txt
✅ Much faster than find (uses database)
💡 Run updatedb to refresh file database
🔍 May not find recently created files until updatedb runs
searchlocatefast

Locate executable commands and their paths

bash
# Find command location
which python
which python3

# Find command, source, and man pages
whereis python

# Show all matches
which -a python
✅ which shows path to executable in PATH
💡 whereis also shows man pages and source files
🔍 Useful for checking which version of a command will run
searchwhichwhereiscommands

Compression & Archives

Create and extract tar archives (tape archives)

bash
# Create archive
tar -cvf archive.tar files/

# Create compressed archive
tar -czvf archive.tar.gz files/    # gzip
tar -cjvf archive.tar.bz2 files/   # bzip2

# Extract archive
tar -xvf archive.tar
tar -xzvf archive.tar.gz

# List contents
tar -tvf archive.tar

# Extract to directory
tar -xzvf archive.tar.gz -C /destination/
✅ c=create, x=extract, v=verbose, f=file, z=gzip, j=bzip2
💡 .tar.gz is most common compressed format
🔍 -C extracts to specific directory
⚡ Remember: "eXtract Ze Files" for -xzf
archivetarcompression

Compress and decompress files with gzip

bash
# Compress file
gzip file.txt          # Creates file.txt.gz

# Decompress
gzip -d file.txt.gz
gunzip file.txt.gz

# Keep original
gzip -k file.txt

# Compress multiple files
gzip file1.txt file2.txt
✅ gzip replaces original file by default
💡 Use -k to keep original file
🔍 gunzip is alias for gzip -d
compressiongzipcompress

Create and extract zip archives (cross-platform)

bash
# Create zip
zip archive.zip file1.txt file2.txt

# Zip directory
zip -r archive.zip directory/

# Extract zip
unzip archive.zip

# Extract to directory
unzip archive.zip -d /destination/

# List contents
unzip -l archive.zip
✅ zip format is cross-platform (Windows compatible)
💡 -r zips directories recursively
🔍 unzip -l lists contents without extracting
archivezipcompressioncross-platform