Top Tags

Ubuntu CLI Handbook

Quick reference for essential Ubuntu/Linux command-line commands — navigation, file management, system config, networking, logs, and more.

Current Directory & Moving Around

bash
1pwd # Print current working directory
2cd /path/to/dir # Change directory
3cd ~ # Go to home directory
4cd - # Go to previous directory
5cd .. # Go up one level
6pushd /path # Push directory onto stack and cd
7popd # Pop directory from stack and cd back

Listing Files

bash
1ls # List files
2ls -la # List all files (including hidden) with details
3ls -lh # Human-readable file sizes
4ls -lt # Sort by modification time (newest first)
5ls -lS # Sort by size (largest first)
6ls -R # List recursively
7ls -i # Show inode numbers
8tree # Show directory tree (install: sudo apt install tree)
9tree -L 2 # Limit tree depth to 2 levels

Finding Files

bash
1find . -name "*.log" # Find files by name
2find . -iname "*.txt" # Case-insensitive search
3find / -type f -size +100M # Files larger than 100 MB
4find . -type f -mtime -7 # Modified in last 7 days
5find . -type f -empty # Find empty files
6find . -type f -ls # Detailed listing of found files
7find . -name "*.tmp" -delete # Find and delete
8locate filename # Fast search (uses index, run sudo updatedb first)
9which command # Show full path of a command
10whereis command # Locate binary, source, man page
11type command # Show how a command would be interpreted

File Operations

Create, Copy, Move, Delete

bash
1touch file.txt # Create empty file / update timestamp
2mkdir dirname # Create directory
3mkdir -p path/to/nested # Create nested directories
4cp file.txt copy.txt # Copy file
5cp -r dir/ dir_copy/ # Copy directory recursively
6mv old.txt new.txt # Rename / move file
7rm file.txt # Delete file
8rm -rf directory/ # Delete directory recursively (use with caution!)
9rmdir empty_dir # Remove empty directory only

Linking

bash
1ln file hardlink # Create hard link
2ln -s /path/to/file symlink # Create symbolic (soft) link
3readlink -f symlink # Resolve full path of a symlink

File Content

bash
1cat file.txt # Print entire file
2less file.txt # Scrollable viewer (q to quit)
3head -n 20 file.txt # First 20 lines
4tail -n 20 file.txt # Last 20 lines
5tail -f /var/log/syslog # Follow file in real-time (great for logs)
6wc -l file.txt # Count lines
7wc -w file.txt # Count words
8diff file1 file2 # Compare two files
9stat file.txt # Detailed file metadata
10file unknown_file # Detect file type

Archiving & Compression

bash
1tar -czf archive.tar.gz dir/ # Create gzipped tar
2tar -xzf archive.tar.gz # Extract gzipped tar
3tar -xzf archive.tar.gz -C /dest/ # Extract to specific directory
4tar -tf archive.tar.gz # List contents without extracting
5zip -r archive.zip dir/ # Create zip
6unzip archive.zip # Extract zip
7gzip file # Compress (replaces original)
8gunzip file.gz # Decompress

Permissions & Ownership

Viewing Permissions

bash
1ls -la # View permissions
2stat -c '%A %a %n' file.txt # Octal + symbolic permissions
3getfacl file.txt # View Access Control Lists

Changing Permissions

bash
1chmod 755 file.txt # rwxr-xr-x
2chmod 644 file.txt # rw-r--r--
3chmod +x script.sh # Add execute permission
4chmod -R 755 directory/ # Recursive permission change

Changing Ownership

bash
1chown user file.txt # Change owner
2chown user:group file.txt # Change owner and group
3chown -R user:group directory/ # Recursive ownership change

ACLs (Access Control Lists)

bash
1setfacl -m u:username:rwx file # Grant user specific access
2getfacl -R /some/path > perms.txt # Backup ACLs
3setfacl --restore=perms.txt # Restore ACLs

grep — Search Inside Files

bash
1grep "pattern" file.txt # Search for pattern
2grep -i "pattern" file.txt # Case-insensitive
3grep -r "pattern" /path/ # Recursive search
4grep -n "pattern" file.txt # Show line numbers
5grep -c "pattern" file.txt # Count matches
6grep -v "pattern" file.txt # Invert match (lines NOT matching)
7grep -l "pattern" *.log # List filenames with matches
8grep -E "foo|bar" file.txt # Extended regex (egrep)

sed — Stream Editor

bash
1sed 's/old/new/' file.txt # Replace first occurrence per line
2sed 's/old/new/g' file.txt # Replace all occurrences
3sed -i 's/old/new/g' file.txt # In-place edit
4sed -n '10,20p' file.txt # Print lines 10-20
5sed '/pattern/d' file.txt # Delete lines matching pattern

awk — Column Processing

bash
1awk '{print $1}' file.txt # Print first column
2awk '{print $1, $3}' file.txt # Print 1st and 3rd columns
3awk -F: '{print $1}' /etc/passwd # Use : as delimiter
4awk '{x += $3} END {print x}' file # Sum values in column 3
5awk 'NR==5,NR==10' file.txt # Print lines 5 to 10

Other Useful Text Tools

bash
1sort file.txt # Sort lines alphabetically
2sort -n file.txt # Sort numerically
3sort -u file.txt # Sort and remove duplicates
4uniq # Remove adjacent duplicates (use with sort)
5cut -d: -f1 /etc/passwd # Cut fields by delimiter
6tr 'a-z' 'A-Z' < file.txt # Translate characters (lowercase → uppercase)
7tee output.txt # Read stdin, write to file AND stdout
8xargs # Build commands from stdin

User & Group Management

User Operations

bash
1whoami # Current username
2id # Current user UID, GID, groups
3id username # Info about specific user
4sudo adduser username # Create new user (interactive)
5sudo useradd username # Create user (non-interactive)
6sudo passwd username # Set/change password
7sudo deluser username # Delete user
8sudo deluser --remove-home user # Delete user + home directory
9su - username # Switch to another user
10sudo -i # Open root shell

Group Operations

bash
1groups # List groups for current user
2groups username # List groups for a user
3sudo addgroup groupname # Create group
4sudo adduser username groupname # Add user to group
5sudo deluser username groupname # Remove user from group
6sudo usermod -aG group username # Append user to group (keeps existing)

Key User Files

bash
1cat /etc/passwd # All user accounts
2cat /etc/group # All groups
3cat /etc/shadow # Password hashes (root only)
4cat /etc/sudoers # Sudoers config (edit with visudo!)

Process Management

Viewing Processes

bash
1ps aux # All running processes
2ps aux | grep nginx # Find specific process
3top # Real-time process monitor
4htop # Better interactive process monitor (install: sudo apt install htop)
5pgrep -a nginx # Find PID by name
6pidof nginx # Get PID of a running program

Controlling Processes

bash
1kill PID # Terminate process (SIGTERM)
2kill -9 PID # Force kill (SIGKILL)
3pkill process_name # Kill by name
4killall process_name # Kill all instances by name

Background & Job Control

bash
1command & # Run in background
2jobs # List background jobs
3fg %1 # Bring job 1 to foreground
4bg %1 # Resume job 1 in background
5nohup command & # Run command immune to hangups
6disown %1 # Detach job from terminal

Resource Usage

bash
1free -h # Memory usage
2uptime # System uptime and load averages
3vmstat 1 # Virtual memory stats (every 1 sec)
4iostat 1 # CPU and I/O stats
5lsof -p PID # Files opened by a process
6lsof -i :80 # What process is using port 80

Disk & Storage

Disk Usage

bash
1df -h # Filesystem disk space usage
2df -i # Inode usage
3du -sh /path # Total size of a directory
4du -sh * # Size of each item in current dir
5du -h --max-depth=1 # One level deep summary
6ncdu / # Interactive disk usage browser (install: sudo apt install ncdu)

Disk & Partitions

bash
1lsblk # List block devices (disks, partitions)
2blkid # Show UUID and filesystem type
3fdisk -l # List partition tables
4mount # Show mounted filesystems
5mount /dev/sdb1 /mnt/data # Mount a partition
6umount /mnt/data # Unmount
7cat /etc/fstab # Permanent mount configuration

Package Management (APT)

Basic APT Commands

bash
1sudo apt update # Refresh package index
2sudo apt upgrade # Upgrade all installed packages
3sudo apt full-upgrade # Upgrade with dependency changes
4sudo apt install package_name # Install a package
5sudo apt remove package_name # Remove a package (keep config)
6sudo apt purge package_name # Remove package + config files
7sudo apt autoremove # Remove unneeded dependencies
8sudo apt search keyword # Search for packages
9sudo apt show package_name # Show package details
10sudo apt list --installed # List all installed packages
11sudo apt list --upgradable # List upgradable packages

DPKG (Low-Level)

bash
1dpkg -l # List all installed packages
2dpkg -l | grep package # Check if a package is installed
3dpkg -S /path/to/file # Which package owns this file?
4dpkg -i package.deb # Install local .deb file
5dpkg --configure -a # Configure partially installed packages
6dpkg --audit # List problematic packages

APT Repositories

bash
1cat /etc/apt/sources.list # Main repo config
2ls /etc/apt/sources.list.d/ # Additional repo configs
3sudo add-apt-repository ppa:name/ppa # Add PPA
4sudo add-apt-repository --remove ppa:name/ppa # Remove PPA

Snap Packages

bash
1snap list # List installed snaps
2sudo snap install package # Install snap
3sudo snap remove package # Remove snap
4sudo snap refresh # Update all snaps
5snap info package # Snap details

Networking

IP & Interfaces

bash
1ip addr show # Show IP addresses (modern)
2ip link show # Show network interfaces
3ip route show # Show routing table / default gateway
4hostname -I # Quick way to get local IP
5ifconfig # Legacy IP info (net-tools)

Connectivity Testing

bash
1ping -c 4 google.com # Ping with 4 packets
2traceroute google.com # Trace route to host
3mtr google.com # Combined ping + traceroute
4curl -I https://example.com # Fetch HTTP headers
5wget https://example.com/file.tar.gz # Download file

DNS

bash
1dig example.com # DNS lookup
2dig +short example.com # Short DNS answer
3nslookup example.com # Legacy DNS lookup
4host example.com # Simple DNS lookup
5cat /etc/resolv.conf # DNS resolver configuration
6resolvectl status # systemd-resolved DNS status

Ports & Connections

bash
1ss -tulnp # List listening ports (modern)
2ss -plat # All TCP connections with processes
3netstat -tulnp # Legacy listening ports
4lsof -iTCP -sTCP:LISTEN -P -n # Listening TCP processes
5nmap -sT localhost # Port scan (install: sudo apt install nmap)

Firewall (UFW)

bash
1sudo ufw status # Show firewall status
2sudo ufw enable # Enable firewall
3sudo ufw disable # Disable firewall
4sudo ufw allow 22/tcp # Allow SSH
5sudo ufw allow 80/tcp # Allow HTTP
6sudo ufw allow 443/tcp # Allow HTTPS
7sudo ufw deny 3306 # Block MySQL port
8sudo ufw delete allow 80/tcp # Remove a rule
9sudo ufw logging on # Enable logging
10sudo ufw reset # Reset all rules

Netplan (Ubuntu Network Config)

bash
1ls /etc/netplan/ # Netplan config files
2cat /etc/netplan/*.yaml # View network config
3sudo netplan apply # Apply network changes
4sudo netplan try # Test config (auto-reverts on failure)

Systemd & Services

Service Management

bash
1sudo systemctl start service # Start a service
2sudo systemctl stop service # Stop a service
3sudo systemctl restart service # Restart a service
4sudo systemctl reload service # Reload config without restart
5sudo systemctl status service # Check service status
6sudo systemctl enable service # Enable on boot
7sudo systemctl disable service # Disable on boot
8sudo systemctl is-active service # Check if active
9sudo systemctl is-enabled service # Check if enabled on boot

Listing & Inspecting

bash
1systemctl list-units --type=service # List running services
2systemctl list-units --type=service --all # List all services
3systemctl list-unit-files # List unit files (enabled/disabled)
4systemctl cat service # Show unit file content
5systemctl show service # Show all properties

System Control

bash
1sudo systemctl daemon-reload # Reload unit files after changes
2sudo systemctl poweroff # Shutdown
3sudo systemctl reboot # Reboot
4sudo systemctl suspend # Suspend
5sudo systemctl hibernate # Hibernate

Timers (Cron Alternative)

bash
1systemctl list-timers # List active timers
2systemctl status snap.certbot.renew.timer # Timer status example

Logs & Journalctl

Journalctl (systemd logs)

bash
1journalctl # All logs
2journalctl -u nginx # Logs for specific service
3journalctl -u nginx --since today # Since today
4journalctl -u nginx --since "1 hour ago"
5journalctl -f # Follow logs in real-time
6journalctl -p err # Only errors
7journalctl -p warning # Warnings and above
8journalctl --disk-usage # Log storage size
9journalctl -b # Logs from current boot
10journalctl -b -1 # Logs from previous boot
11journalctl --list-boots # List all boot sessions

Traditional Log Files

bash
1# Most logs are in /var/log/
2ls /var/log/
3
4# Key log files:
5cat /var/log/syslog # General system log
6cat /var/log/auth.log # Authentication & sudo logs
7cat /var/log/kern.log # Kernel messages
8cat /var/log/dpkg.log # Package manager log
9cat /var/log/apt/history.log # APT install history
10cat /var/log/boot.log # Boot messages
11cat /var/log/ufw.log # Firewall log (if UFW enabled)
12
13# Nginx / Apache logs:
14cat /var/log/nginx/access.log
15cat /var/log/nginx/error.log
16cat /var/log/apache2/access.log
17cat /var/log/apache2/error.log
18
19# MySQL / MariaDB:
20cat /var/log/mysql/error.log
21
22# Follow logs in real-time:
23tail -f /var/log/syslog

dmesg (Kernel Ring Buffer)

bash
1dmesg # All kernel messages
2dmesg | tail -20 # Last 20 kernel messages
3dmesg -T # Human-readable timestamps
4dmesg --level=err # Only errors
5dmesg -w # Follow in real-time

Important Config File Locations

Quick reference for where Ubuntu stores key configuration files:

System

File / DirectoryPurpose
/etc/hostnameSystem hostname
/etc/hostsStatic host-to-IP mappings
/etc/fstabFilesystem mount table
/etc/environmentSystem-wide environment variables
/etc/timezoneTimezone setting
/etc/locale.genLocale configuration
/etc/default/grubGRUB bootloader config
/etc/crontabSystem-wide cron jobs
/etc/sysctl.confKernel parameters

Networking

File / DirectoryPurpose
/etc/netplan/*.yamlNetwork config (Ubuntu 18.04+)
/etc/resolv.confDNS resolver
/etc/hosts.allowTCP wrappers allow
/etc/hosts.denyTCP wrappers deny

Security & Users

File / DirectoryPurpose
/etc/passwdUser accounts
/etc/shadowPassword hashes
/etc/groupGroup definitions
/etc/sudoersSudo access (edit with visudo)
/etc/ssh/sshd_configSSH server config
/etc/pam.d/PAM authentication modules

Services

File / DirectoryPurpose
/etc/nginx/Nginx config
/etc/apache2/Apache config
/etc/mysql/MySQL / MariaDB config
/etc/docker/daemon.jsonDocker daemon config
/etc/systemd/system/Custom systemd unit files

Package Management

File / DirectoryPurpose
/etc/apt/sources.listAPT repositories
/etc/apt/sources.list.d/Additional repos
/etc/apt/apt.conf.d/APT configuration fragments

Shell

File / DirectoryPurpose
~/.bashrcPer-user Bash config (interactive)
~/.bash_profilePer-user login shell config
~/.profilePer-user profile (used by many shells)
/etc/bash.bashrcSystem-wide Bash config
/etc/profileSystem-wide login shell profile
/etc/profile.d/Drop-in profile scripts

SSH

Connecting

bash
1ssh user@host # Connect to remote host
2ssh -p 2222 user@host # Custom port
3ssh -i ~/.ssh/key.pem user@host # Specify private key
4ssh -L 8080:localhost:80 user@host # Local port forwarding
5ssh -J jumphost user@target # Jump through bastion host

Key Management

bash
1ssh-keygen -t ed25519 -C "[email protected]" # Generate key pair
2ssh-copy-id user@host # Copy public key to server
3cat ~/.ssh/authorized_keys # View authorized keys
4eval "$(ssh-agent -s)" && ssh-add ~/.ssh/key # Start agent & add key

SSH Config File

bash
1cat ~/.ssh/config # Per-user SSH config

Example ~/.ssh/config:

text
1Host myserver
2 HostName 192.168.1.100
3 User admin
4 Port 22
5 IdentityFile ~/.ssh/mykey

Cron & Scheduled Tasks

Crontab

bash
1crontab -e # Edit current user's crontab
2crontab -l # List current crontab
3crontab -r # Remove current crontab
4sudo crontab -u user -e # Edit another user's crontab

Cron Syntax

text
1# ┌───────────── minute (0–59)
2# │ ┌───────────── hour (0–23)
3# │ │ ┌───────────── day of month (1–31)
4# │ │ │ ┌───────────── month (1–12)
5# │ │ │ │ ┌───────────── day of week (0–7, 0 & 7 = Sunday)
6# │ │ │ │ │
7# * * * * * command_to_run
8
9# Examples:
100 2 * * * /usr/local/bin/backup.sh # Daily at 2:00 AM
11*/15 * * * * /usr/bin/check-health.sh # Every 15 minutes
120 0 * * 0 /usr/local/bin/weekly.sh # Weekly on Sunday midnight
13@reboot /usr/local/bin/on-startup.sh # Run at boot

Cron Directories (Drop-In Scripts)

bash
1ls /etc/cron.d/ # Custom cron files
2ls /etc/cron.daily/ # Runs daily
3ls /etc/cron.hourly/ # Runs hourly
4ls /etc/cron.weekly/ # Runs weekly
5ls /etc/cron.monthly/ # Runs monthly

System Information

Hardware & OS

bash
1uname -a # Kernel & OS info
2lsb_release -a # Ubuntu version details
3cat /etc/os-release # OS release info
4hostnamectl # Hostname and OS details
5arch # CPU architecture
6lscpu # CPU info
7lsmem # Memory info
8lspci # PCI devices
9lsusb # USB devices
10lshw -short # Full hardware summary
11dmidecode -t memory # Detailed RAM info (root)

System Resources

bash
1free -h # Memory usage
2uptime # Uptime & load
3cat /proc/cpuinfo # CPU details
4cat /proc/meminfo # Memory details
5nproc # Number of CPU cores

Date & Time

bash
1date # Current date/time
2timedatectl # Timezone & NTP status
3sudo timedatectl set-timezone America/New_York # Set timezone

Environment Variables

bash
1env # List all environment variables
2echo $PATH # Print specific variable
3echo $HOME # Home directory
4export VAR="value" # Set variable for current session
5printenv VAR # Print variable value

Making Variables Persistent

bash
1# For current user — add to ~/.bashrc:
2echo 'export MY_VAR="value"' >> ~/.bashrc
3source ~/.bashrc
4
5# System-wide — add to /etc/environment:
6sudo nano /etc/environment
7# Add: MY_VAR="value"

Useful One-Liners & Tips

History

bash
1history # Show command history
2history | grep ssh # Search history
3!! # Repeat last command
4!$ # Last argument of previous command
5ctrl+r # Reverse search in history

Piping & Redirection

bash
1command > file.txt # Redirect stdout to file (overwrite)
2command >> file.txt # Append stdout to file
3command 2> error.log # Redirect stderr
4command &> all.log # Redirect both stdout and stderr
5command1 | command2 # Pipe stdout to next command
6command | tee file.txt # Pipe and save to file simultaneously

Handy Shortcuts

bash
1ctrl+c # Cancel current command
2ctrl+z # Suspend current command
3ctrl+d # Logout / end input
4ctrl+l # Clear screen
5ctrl+a # Move cursor to beginning of line
6ctrl+e # Move cursor to end of line
7ctrl+w # Delete word before cursor
8ctrl+u # Delete from cursor to beginning of line
9ctrl+k # Delete from cursor to end of line
10tab # Auto-complete

Quick Operations

bash
1alias ll='ls -la' # Create an alias
2sudo !! # Run last command as sudo
3watch -n 5 'df -h' # Repeat command every 5 seconds
4time command # Measure execution time
5yes | command # Auto-confirm prompts
6command1 && command2 # Run command2 only if command1 succeeds
7command1 || command2 # Run command2 only if command1 fails