🐧 Linux Command Cheat Sheet

APACHE

Commands

apachectl -t : Test configuration
apachectl restart : Restart service
apachectl graceful : Graceful restart
apachectl stop : Stop service
systemctl start apache2 : Start (systemd)
systemctl status apache2 : Check status

Common Directories

/etc/apache2 : Configuration (Debian)
/etc/httpd : Configuration (RHEL)
/var/www/html : Default web root
/var/log/apache2 : Log files (Debian)
/var/log/httpd : Log files (RHEL)

Log Monitoring

tail -f /var/log/apache2/access.log
tail -f /var/log/apache2/error.log

Configuration Tips

Virtual hosts in /etc/apache2/sites-available/
Enable site: a2ensite example.com
Disable site: a2dissite example.com
Modules: a2enmod, a2dismod

BASE

Basic Linux Commands

pwd : Print working directory
ls : List directory contents
ls -l : Long listing format
ls -a : Show hidden files
cd : Change directory
cd ~ : Go to home directory
cd - : Go to previous directory
cp : Copy files or directories
cp -r : Recursive copy (for directories)
mv : Move/rename files
rm : Remove files
rm -rf : Force recursive removal (dangerous)
mkdir : Create directory
rmdir : Remove empty directory
cat : Display file contents
less : View file page by page
head : Show first lines of file
tail : Show last lines of file
tail -f : Follow log file
grep : Search text patterns
grep -r : Recursive search
find : Search for files
find . -name "*.txt" : Find all txt files
chmod : Change file permissions
chown : Change file owner
tar : Archive files
tar -czvf : Create gzipped tar archive
tar -xzvf : Extract gzipped tar archive
df : Disk space usage
du : Directory space usage
du -sh : Human-readable summary
top : Display processes
htop : Interactive process viewer
ps : Process status
ps aux : Show all processes
kill : Terminate process
kill -9 : Force kill

DOCKER

Commands

docker ps : List running containers
docker ps -a : List all containers
docker images : List images
docker run : Run a container
docker run -it : Interactive terminal
docker run -d : Detached mode
docker run -p 8080:80 : Port mapping
docker stop : Stop container
docker start : Start stopped container
docker rm : Remove container
docker rm -f : Force remove running container
docker rmi : Remove image
docker build : Build image from Dockerfile
docker pull : Pull image from registry
docker push : Push image to registry
docker logs : View container logs
docker logs -f : Follow log output
docker exec : Execute command in running container
docker exec -it /bin/bash : Get shell in container
docker volume : Manage volumes
docker network : Manage networks
docker-compose up : Start services
docker-compose down : Stop services
docker system prune : Clean up unused objects
docker info : Display system information

FILE PERMISSIONS

Common Permission Values

chmod 400 file : Read by owner only
chmod 600 file : Read/write by owner only
chmod 644 file : Owner read/write, others read
chmod 755 file : Owner read/write/execute, others read/execute
chmod 777 file : Read/write/execute for everyone (dangerous)

Symbolic Permissions

chmod u+x file : Add execute for owner
chmod g-w file : Remove write for group
chmod o=r file : Others can only read
chmod a+x file : Add execute for all (a = all)

COMMON PORTS

20/21 : FTP
22 : SSH
25 : SMTP
53 : DNS
80 : HTTP
110 : POP3
143 : IMAP
443 : HTTPS
3306 : MySQL
5432 : PostgreSQL
6379 : Redis
8080 : HTTP Alt
27017 : MongoDB

SYSTEM INFO

Hardware Information

lscpu : CPU information
free -h : Memory usage
df -h : Disk space
lspci : List PCI devices
lsusb : List USB devices

System Information

uname -a : Kernel info
hostnamectl : Hostname and OS info
uptime : System uptime
who : Logged in users
w : Who is logged in and what they're doing

FILESYSTEM

Mounting and Unmounting

mount : Mount filesystem
mount -a : Mount all in fstab
umount : Unmount filesystem

Disk Usage

df : Disk space usage
df -h : Human-readable
du : Directory space usage
du -sh * : Summary per directory

Partition Management

lsblk : List block devices
blkid : Show block device attributes
fdisk : Partition table manipulator
parted : Advanced partition tool

Filesystem Operations

mkfs : Create filesystem
mkfs.ext4 : Create ext4 fs
fsck : Filesystem check
fsck -y : Auto-repair
tune2fs : Tune ext filesystem

Advanced Operations

dd : Low-level copy
dd if=/dev/zero of=file bs=1M count=100
ln : Create links
ln -s : Symbolic link
findmnt : Show mounted filesystems

GIT

Repository Basics

git init : Initialize new repository
git clone : Clone a repository
git status : Show working tree status

Staging and Committing

git add : Add files to staging
git add . : Add all files
git commit : Commit changes
git commit -m "message" : Commit with message

Remote Operations

git push : Push to remote repository
git pull : Fetch and merge from remote

Branching

git branch : List/create branches
git branch -d : Delete branch
git checkout : Switch branches
git checkout -b : Create and switch to new branch

Merging and Rebasing

git merge : Merge branches
git rebase : Reapply commits on top of another branch

History and Inspection

git log : Show commit logs
git log --oneline : Compact log view
git diff : Show changes

Miscellaneous

git stash : Stash changes temporarily
git remote : Manage remote repositories
git reset : Reset current HEAD
git reset --hard : Discard all changes
git tag : Create/list tags
git config : Configure settings

JOURNALCTL

Basic Log Viewing

journalctl : Show all logs
journalctl -u : Show logs for service
journalctl -u nginx : Example for nginx
journalctl -f : Follow logs (tail -f)

Boot-Specific Logs

journalctl -b : Current boot logs
journalctl -k : Kernel messages

Time Filtering

journalctl --since : Filter by time
journalctl --since "2023-01-01" : Specific date
journalctl --since "1 hour ago" : Relative time
journalctl --until : Filter end time

Priority Filtering

journalctl -p : Priority filter
journalctl -p err : Only errors

Output Control

journalctl -n : Show n entries
journalctl -n 50 : Show last 50 entries
journalctl --no-pager : Disable pager
journalctl -o : Output format
journalctl -o json : JSON format

Log Maintenance

journalctl --disk-usage : Show log size
journalctl --vacuum-size= : Clean logs
journalctl --vacuum-size=500M : Keep 500MB of logs

NETWORKING

Interface Configuration

ip addr : Show IP addresses (modern)
ifconfig : Show network interfaces (deprecated)

Connectivity Testing

ping : Test network connectivity
ping -c 4 : Send 4 packets
traceroute : Trace network path
mtr : Network diagnostic tool

Port and Connection Info

netstat : Network statistics
netstat -tulnp : Show listening ports
ss : Socket statistics (modern netstat)
ss -tulnp : Show listening ports

DNS Operations

dig : DNS lookup
nslookup : DNS query tool
whois : Domain information
host : DNS lookup utility

Routing

route : Show routing table
route -n : Numerical addresses

Wireless

iwconfig : Wireless interface config
nmcli : NetworkManager command line

File Transfer

curl : Transfer data from URLs
curl -I : Show headers only
wget : Download files
wget -c : Continue interrupted download
scp : Secure copy between hosts
rsync : Remote file sync
rsync -avz : Archive, verbose, compress

Advanced Tools

nc/netcat : Network swiss army knife
tcpdump : Network packet analyzer
tcpdump -i eth0 : Capture on interface

NGINX

Service Management

nginx -t : Test configuration
nginx -s reload : Reload config
nginx -s stop : Fast shutdown
systemctl start nginx : Start service
systemctl stop nginx : Stop service
systemctl restart nginx : Restart service
systemctl status nginx : Check status

Important Directories

/etc/nginx : Configuration
/var/log/nginx : Log files
/usr/share/nginx/html : Default web root

Log Monitoring

tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log

Configuration Tips

server blocks in /etc/nginx/sites-available/
ln -s /etc/nginx/sites-available/example /etc/nginx/sites-enabled/ : Enable site

PACKAGE MANAGERS

APT (Debian/Ubuntu)

apt update : Update package list
apt upgrade : Upgrade packages
apt install : Install package
apt remove : Remove package
apt purge : Remove with configs
apt search : Search packages
apt show : Show package info
apt list --installed : List installed
apt autoremove : Remove unused packages

YUM/DNF (RHEL/Fedora)

dnf install : Install package
dnf remove : Remove package
dnf update : Update packages
dnf search : Search packages
dnf info : Show package info
dnf list installed : List installed

Pacman (Arch)

pacman -S : Install package
pacman -R : Remove package
pacman -Syu : Full system upgrade
pacman -Qs : Search installed
pacman -Si : Show package info

Snap

snap install : Install snap
snap remove : Remove snap
snap list : List installed
snap refresh : Update snaps

Flatpak

flatpak install : Install package
flatpak uninstall : Remove package
flatpak list : List installed
flatpak update : Update packages

PERMISSIONS

Basic Permissions

chmod 755 : rwxr-xr-x
chmod +x : Add execute permission
chmod -R : Recursive change
chown user:group : Change owner and group
chown -R : Recursive owner change
chgrp : Change group ownership

Advanced Controls

umask : Set default permissions
stat -c %a : Show octal permissions
getfacl : View ACLs
setfacl -m u:user:rwx : Add user ACL
setfacl -x u:user : Remove user ACL

User/Group Info

id : Show user/group IDs
groups : Show user's groups
newgrp : Temporarily change primary group

SSH

Basic Connections

ssh user@host : Connect to remote host
ssh -p 2222 : Custom port
ssh -v : Verbose mode

Key Management

ssh-keygen -t rsa -b 4096 : Create key pair
ssh-copy-id user@host : Copy key to remote
ssh-agent : Manage keys
ssh-add : Add keys to agent

File Transfer

scp file user@host:path : Secure copy
sftp user@host : Secure FTP

Port Forwarding

ssh -D 1080 : SOCKS proxy
ssh -L : Local port forwarding
ssh -R : Remote port forwarding
ssh -X : X11 forwarding

Configuration

~/.ssh/config : Client config
/etc/ssh/sshd_config : Server config

SYSTEMD

Service Management

systemctl start : Start service
systemctl stop : Stop service
systemctl restart : Restart service
systemctl reload : Reload configuration
systemctl status : Check service status

Boot Configuration

systemctl enable : Enable at boot
systemctl disable : Disable at boot
systemctl is-enabled : Check boot status
systemctl mask : Completely disable
systemctl unmask : Remove mask

System Inspection

systemctl list-units : List all units
systemctl list-units --type=service : List services
systemctl list-timers : List timers
systemctl daemon-reload : Reload config

TMUX

Sessions

tmux new -s name : New named session
tmux ls : List sessions
tmux attach -t name : Attach to session
tmux kill-session -t name : Kill session

Windows (Prefix +)

c : Create window
n : Next window
p : Previous window
& : Kill window
, : Rename window

Panes (Prefix +)

% : Vertical split
" : Horizontal split
arrow : Switch panes
x : Kill pane
z : Zoom pane
space : Toggle layouts

Miscellaneous

d : Detach session
[ : Enter copy mode
] : Paste
$ : Rename session
: : Command prompt

UFW

Basic Controls

ufw enable : Enable firewall
ufw disable : Disable firewall
ufw status : Show status
ufw status verbose : Detailed status

Default Policies

ufw default deny : Deny all incoming
ufw default allow : Allow all incoming

Rule Management

ufw allow 22 : Allow SSH
ufw allow 80/tcp : Allow HTTP
ufw allow from 192.168.1.100 : Allow from IP
ufw deny 23 : Deny Telnet
ufw delete allow 22 : Delete SSH rule

Advanced

ufw reset : Reset all rules
ufw logging on : Enable logging
ufw app list : List application profiles
ufw app info : Show profile info

USERS

User Information

whoami : Current user
id : User and group info
who : Logged in users
w : Users and activities
last : Last logins

User Management

useradd -m : Create user with home
useradd -G : Add to groups
usermod -aG : Append to groups
userdel -r : Remove user and home
passwd -l : Lock account
passwd -u : Unlock account

Group Management

groupadd : Create group
groupmod : Modify group
groupdel : Delete group
newgrp : Change primary group

Privileges

sudo : Execute as superuser
visudo : Edit sudoers safely
su - : Login as user with env

VIM

Movement

h : Left
j : Down
k : Up
l : Right
0 : Start of line
$ : End of line
gg : First line
G : Last line

Editing

i : Insert mode
a : Append after cursor
o : New line below
O : New line above
dd : Delete line
yy : Yank (copy) line
p : Paste after

Search/Replace

/pattern : Search forward
?pattern : Search backward
:%s/old/new/g : Replace all

File Operations

:w : Save
:q : Quit
:wq : Save and quit
:q! : Quit without saving

KERNEL

Kernel Information

uname -r : Show kernel version
uname -a : Show all system info
cat /proc/version : Kernel version with compiler
dmesg : Kernel ring buffer messages
dmesg -H : Human-readable with timestamps

Module Management

lsmod : List loaded modules
modinfo : Show module information
modprobe : Load kernel module
rmmod : Remove kernel module
depmod : Generate modules.dep

Kernel Parameters

sysctl -a : List all kernel parameters
sysctl -w parameter=value : Set parameter
cat /proc/sys/kernel/ : View kernel settings

CRON

Crontab Management

crontab -e : Edit user crontab
crontab -l : List cron jobs
crontab -r : Remove all cron jobs
systemctl status cron : Check cron service

System Crontabs

/etc/crontab : System crontab
/etc/cron.d/ : System cron jobs
/etc/cron.hourly/ : Hourly jobs
/etc/cron.daily/ : Daily jobs

Cron Syntax

* * * * * command : Minute Hour Day Month DayOfWeek
@reboot command : Run at boot
@daily command : Run daily

LOGS

System Logs

/var/log/syslog : Main system log
/var/log/auth.log : Authentication logs
/var/log/kern.log : Kernel logs
/var/log/boot.log : Boot messages

Log Rotation

logrotate -f /etc/logrotate.conf : Force rotation
/etc/logrotate.d/ : Custom rotation configs

Log Analysis

grep "error" /var/log/syslog : Filter errors
tail -n 100 /var/log/syslog : Last 100 lines
zgrep "pattern" /var/log/syslog.*.gz : Search rotated logs

SSL/TLS

Certificate Inspection

openssl x509 -in cert.pem -text : View certificate
openssl s_client -connect host:443 : Test connection
openssl req -text -in request.csr : View CSR

Key Generation

openssl genrsa -out key.pem 2048 : Generate RSA key
openssl ecparam -genkey -name secp384r1 -out key.pem : Generate EC key
openssl req -new -key key.pem -out request.csr : Generate CSR

Certificate Conversion

openssl x509 -in cert.cer -out cert.pem : Convert to PEM
openssl pkcs12 -in cert.pfx -out cert.pem : Extract from PFX

COMPRESSION

Archive Commands

tar -czvf archive.tar.gz dir/ : Create gzip tar
tar -xzvf archive.tar.gz : Extract gzip tar
tar -cjvf archive.tar.bz2 dir/ : Create bzip2 tar
tar -xjvf archive.tar.bz2 : Extract bzip2 tar

Compression Tools

gzip file : Compress to .gz
gunzip file.gz : Decompress .gz
bzip2 file : Compress to .bz2
bunzip2 file.bz2 : Decompress .bz2
xz file : Compress to .xz
unxz file.xz : Decompress .xz

Zip Archives

zip -r archive.zip dir/ : Create zip
unzip archive.zip : Extract zip
7z a archive.7z dir/ : Create 7z
7z x archive.7z : Extract 7z

PROCESS MONITORING

Process Inspection

ps aux : Show all processes
ps -ef : Full format listing
pgrep process : Find process ID
pstree : Show process tree

Resource Monitoring

top : Interactive process viewer
htop : Enhanced process viewer
iotop : Disk I/O monitoring
iftop : Network bandwidth monitoring

Process Control

kill -9 PID : Force kill process
pkill process : Kill by name
killall process : Kill all matching
nice -n 10 command : Run with low priority
renice 5 -p PID : Change priority

SELINUX

Status Management

getenforce : Check status
setenforce 1 : Enable enforcing
setenforce 0 : Set permissive
sestatus : Detailed status

Context Management

ls -Z : Show SELinux contexts
chcon -t type file : Change file type
restorecon file : Restore default context

Troubleshooting

audit2allow : Generate policy from logs
sealert -a /var/log/audit/audit.log : Analyze alerts
semodule -l : List modules

LVM

Physical Volumes

pvcreate /dev/sdb1 : Create PV
pvdisplay : Show PVs
pvs : Brief PV status

Volume Groups

vgcreate vg_name /dev/sdb1 : Create VG
vgextend vg_name /dev/sdc1 : Extend VG
vgdisplay : Show VG info

Logical Volumes

lvcreate -L 10G -n lv_name vg_name : Create LV
lvextend -L +5G /dev/vg_name/lv_name : Extend LV
lvresize -L 20G /dev/vg_name/lv_name : Resize LV
lvdisplay : Show LV info

ENVIRONMENT

Variable Management

env : Show all variables
echo $VAR : Show variable
export VAR=value : Set variable
unset VAR : Remove variable

Path Management

echo $PATH : Show path
export PATH=$PATH:/new/path : Add to path

Shell Configuration

source ~/.bashrc : Reload bash config
. ~/.profile : Reload profile
alias ll='ls -la' : Create alias
unalias ll : Remove alias

TIME

Date/Time Management

date : Show current date/time
date +%s : Unix timestamp
timedatectl : System time control
ntpdate pool.ntp.org : Sync time with NTP

Time Zone

timedatectl list-timezones : List timezones
timedatectl set-timezone Zone : Set timezone
ln -sf /usr/share/zoneinfo/Zone /etc/localtime : Alternative method

Command Timing

time command : Measure execution time
timeout 10s command : Run with timeout