The Linux commands you need daily — navigation, permissions, processes, networking, package management, and shell tricks. All in one place, copy-paste ready.
Quick reference
| Category | Command | What it does |
|---|---|---|
| Navigation | pwd |
Print current directory |
| Navigation | ls -la |
List all files (long format) |
| Navigation | cd - |
Go to previous directory |
| Files | cp -r src/ dst/ |
Copy directory recursively |
| Files | mv old new |
Move or rename |
| Files | rm -rf dir/ |
Remove directory (irreversible) |
| Files | find . -name "*.log" |
Find files by name |
| Text | grep -rn "pattern" . |
Search with line numbers |
| Text | tail -f /var/log/syslog |
Follow live log |
| Text | less file.txt |
Page through file |
| Permissions | chmod 755 script.sh |
Set rwxr-xr-x |
| Permissions | chown user:group file |
Change owner |
| Processes | ps aux | grep nginx |
Find process |
| Processes | kill -9 PID |
Force kill process |
| Disk | df -h |
Disk usage (human-readable) |
| Disk | du -sh dir/ |
Directory size |
| Network | ss -tlnp |
Open TCP ports |
| Network | curl -I https://example.com |
Check HTTP headers |
| Users | whoami |
Current user |
| Users | sudo -i |
Root shell |
| Packages | apt update && apt upgrade |
Update (Debian/Ubuntu) |
| Packages | yum update |
Update (RHEL/CentOS) |
| Archive | tar -czf out.tar.gz dir/ |
Create gzip tarball |
| Archive | tar -xzf file.tar.gz |
Extract tarball |
File system navigation
# Current location
pwd # /home/user/projects
# List files
ls # basic
ls -l # long format
ls -la # include hidden files
ls -lh # human-readable sizes
ls -lt # sorted by modification time
ls -lS # sorted by size
# Navigate
cd /var/log # absolute path
cd ../.. # two levels up
cd - # previous directory
cd ~ # home directory
cd ~/projects # home subdirectory
# Create directories
mkdir logs # single
mkdir -p a/b/c # nested (no error if exists)
# Find files
find . -name "*.conf" # by name
find /etc -name "*.conf" -type f # files only
find . -mtime -7 # modified in last 7 days
find . -size +100M # larger than 100 MB
find . -name "*.log" -delete # find and delete
find . -type f -exec chmod 644 {} \; # find and apply command
File operations
# Copy
cp file.txt backup.txt # copy file
cp -r src/ dst/ # copy directory recursively
cp -rp src/ dst/ # preserve permissions/timestamps
cp -u src/ dst/ # only newer files
# Move / rename
mv old.txt new.txt # rename
mv file.txt /tmp/ # move to directory
mv *.log /var/log/archive/ # move with glob
# Delete
rm file.txt # delete file
rm -rf dir/ # delete directory (careful!)
rm -i file.txt # prompt before delete
# Links
ln -s /etc/nginx/nginx.conf nginx.conf # symlink
ln file.txt hardlink.txt # hard link
readlink -f symlink # resolve symlink target
# Inspect
file image.png # file type
stat file.txt # detailed metadata
wc -l file.txt # line count
wc -c file.txt # byte count
Viewing and editing files
# View
cat file.txt # print entire file
cat -n file.txt # with line numbers
less file.txt # paginate (q to quit, / to search)
more file.txt # simpler pager
head -n 20 file.txt # first 20 lines
tail -n 50 file.txt # last 50 lines
tail -f /var/log/nginx/access.log # follow live (Ctrl+C to stop)
tail -F file.log # follow even if file rotates
# Quick edit
nano file.txt # beginner-friendly editor
vi file.txt # Vi (universal, always available)
# vi: i = insert, Esc = normal, :wq = save+quit, :q! = quit without saving
# Create / overwrite
echo "hello" > file.txt # overwrite
echo "world" >> file.txt # append
cat > file.txt <<EOF # heredoc
Line one
Line two
EOF
Text processing
# grep — search
grep "error" app.log # basic search
grep -i "error" app.log # case-insensitive
grep -n "error" app.log # show line numbers
grep -r "TODO" src/ # recursive
grep -l "TODO" src/ # filenames only
grep -v "DEBUG" app.log # invert (exclude matches)
grep -c "error" app.log # count matches
grep -A 3 -B 3 "error" app.log # 3 lines of context
grep -E "err|warn|crit" app.log # extended regex (OR)
# sed — stream editor
sed 's/foo/bar/' file.txt # replace first occurrence per line
sed 's/foo/bar/g' file.txt # replace all occurrences
sed -i 's/foo/bar/g' file.txt # in-place edit
sed -n '10,20p' file.txt # print lines 10–20
sed '/^#/d' file.txt # delete comment lines
# awk — column processing
awk '{print $1}' file.txt # first column
awk -F: '{print $1}' /etc/passwd # custom delimiter
awk '{sum += $3} END {print sum}' data.txt # sum column 3
awk 'NR==5' file.txt # print line 5
awk '$3 > 100 {print $1, $3}' file.txt # conditional
# sort, uniq, cut
sort file.txt # alphabetical
sort -n numbers.txt # numeric
sort -rn numbers.txt # reverse numeric
sort -u file.txt # sort + deduplicate
uniq -c file.txt # count consecutive duplicates
sort file.txt | uniq -c | sort -rn # frequency count
cut -d: -f1 /etc/passwd # first field, colon-delimited
cut -c1-10 file.txt # first 10 characters per line
# tr, wc, diff
tr 'a-z' 'A-Z' < file.txt # lowercase to uppercase
tr -d '\r' < windows.txt # remove CR (Windows line endings)
wc -l file.txt # line count
wc -w file.txt # word count
diff file1.txt file2.txt # compare files
diff -u file1.txt file2.txt # unified diff (for patches)
File permissions
Linux permissions: rwxrwxrwx = owner / group / others
-rwxr-xr-- 1 alice devs 4096 Jul 15 10:00 script.sh
│││ │││ │││
│││ │││ └── other: r-- = read only
│││ └───── group: r-x = read + execute
└───────── owner: rwx = read + write + execute
# chmod — change permissions
chmod 755 script.sh # rwxr-xr-x (executable script)
chmod 644 config.conf # rw-r--r-- (config file)
chmod 600 secret.key # rw------- (private key)
chmod 777 dir/ # rwxrwxrwx (avoid in production)
chmod +x script.sh # add execute for all
chmod -w file.txt # remove write for all
chmod o-r private.txt # remove read from others
chmod -R 755 dir/ # recursive
# chmod numeric reference
# 4 = read 2 = write 1 = execute
# 7 = rwx 6 = rw- 5 = r-x 4 = r-- 0 = ---
# chown — change owner
chown alice file.txt # change user
chown alice:devs file.txt # change user and group
chown -R www-data:www-data /var/www/html # recursive
# chgrp — change group
chgrp devs file.txt
# View permissions
ls -la file.txt
stat file.txt
# Special bits
chmod u+s /usr/bin/passwd # setuid (run as owner)
chmod g+s dir/ # setgid (new files inherit group)
chmod +t /tmp # sticky bit (only owner can delete)
Processes
# View processes
ps aux # all processes (BSD syntax)
ps -ef # all processes (POSIX syntax)
ps aux | grep nginx # find specific process
pgrep nginx # PID only
pidof nginx # PID of named process
# Real-time monitoring
top # interactive process viewer
htop # better top (may need install)
# top shortcuts: q=quit, k=kill, r=renice, 1=per-CPU, M=sort by mem
# Signals / kill
kill PID # send SIGTERM (graceful)
kill -9 PID # send SIGKILL (force)
kill -HUP PID # reload config (SIGHUP)
killall nginx # kill by name
pkill -f "python app.py" # kill by full command match
# Background jobs
command & # run in background
jobs # list background jobs
fg %1 # bring job 1 to foreground
bg %1 # resume job 1 in background
nohup command & # keep running after logout
disown %1 # detach job from shell
# Process niceness (priority)
nice -n 10 command # lower priority (10 = nicer)
renice -n -5 -p PID # change priority of running process
# Range: -20 (highest) to 19 (lowest). Default: 0
# System resource limits
ulimit -a # show all limits
ulimit -n 65536 # set open file limit
Users and groups
# Current user info
whoami # username
id # uid, gid, groups
id alice # info for another user
groups # groups for current user
who # logged-in users
w # who + what they're doing
last # login history
# Switch user
su alice # switch to alice (needs password)
su - # switch to root (login shell)
sudo command # run as root
sudo -i # root interactive shell
sudo -u alice command # run as alice
# User management (root required)
useradd -m alice # create user with home dir
useradd -m -s /bin/bash -G sudo alice # with shell + sudo group
passwd alice # set password
usermod -aG docker alice # add to group (no -a = removes others)
usermod -s /bin/bash alice # change shell
userdel alice # delete user
userdel -r alice # delete user + home dir
# Group management
groupadd devs # create group
groupdel devs # delete group
gpasswd -a alice devs # add alice to devs
gpasswd -d alice devs # remove alice from devs
# Files
cat /etc/passwd # user accounts (user:x:uid:gid:info:home:shell)
cat /etc/group # groups
cat /etc/shadow # hashed passwords (root only)
# sudoers
visudo # edit /etc/sudoers safely
# alice ALL=(ALL:ALL) ALL # full sudo for alice
# %devs ALL=(ALL) NOPASSWD: /usr/bin/docker # group, no password
Disk and storage
# Disk usage
df -h # disk space (all filesystems)
df -h /var # specific filesystem
du -sh /var/log # directory size (summary)
du -sh * # size of each item in current dir
du -h --max-depth=1 /var # one level deep
ncdu / # interactive disk usage (install first)
# Mount / unmount
lsblk # list block devices (tree view)
lsblk -f # with filesystem types and UUIDs
fdisk -l # list partitions (root)
mount # show all mounts
mount /dev/sdb1 /mnt/disk # mount device
umount /mnt/disk # unmount
mount -o remount,ro / # remount root read-only
# /etc/fstab — persistent mounts
# UUID=abc123 /mnt/data ext4 defaults 0 2
# Check filesystem
fsck /dev/sdb1 # check (unmount first!)
e2fsck -f /dev/sdb1 # force check ext4
# Disk I/O
iostat -x 1 # I/O stats every 1 second
iotop # per-process I/O (needs root)
# LVM basics
pvdisplay # physical volumes
vgdisplay # volume groups
lvdisplay # logical volumes
lvextend -L +10G /dev/vg0/data # extend logical volume
resize2fs /dev/vg0/data # resize filesystem after extend
Networking
# IP addresses
ip addr show # all interfaces
ip addr show eth0 # specific interface
hostname -I # all IP addresses
curl ifconfig.me # public IP address
# Routing
ip route show # routing table
ip route add 192.168.2.0/24 via 192.168.1.1 # add route
ip route del 192.168.2.0/24 # delete route
# Open ports / connections
ss -tlnp # listening TCP ports
ss -ulnp # listening UDP ports
ss -anp # all connections
ss -s # summary
netstat -tlnp # older alternative to ss
# DNS
dig example.com # DNS lookup
dig example.com A # A records only
dig -x 8.8.8.8 # reverse lookup
nslookup example.com # simpler DNS query
host example.com # compact DNS lookup
cat /etc/resolv.conf # DNS server config
# Connectivity
ping -c 4 8.8.8.8 # 4 ICMP packets
traceroute 8.8.8.8 # route to host
mtr 8.8.8.8 # continuous traceroute (better)
curl -I https://example.com # HTTP headers
wget -q -O /dev/null https://example.com # test download
# Transfer files
scp file.txt user@host:/tmp/ # copy to remote
scp -r dir/ user@host:/remote/dir/ # copy directory
rsync -avz src/ user@host:/dst/ # sync (with compression)
rsync -avz --delete src/ dst/ # sync + delete extras
# Firewall (ufw — Ubuntu)
ufw status # show rules
ufw enable # enable firewall
ufw allow 22/tcp # allow SSH
ufw allow 80,443/tcp # allow web
ufw deny 23 # deny telnet
ufw delete allow 80/tcp # remove rule
# Firewall (firewalld — RHEL/CentOS)
firewall-cmd --state
firewall-cmd --list-all
firewall-cmd --add-service=http --permanent
firewall-cmd --reload
Package management
# Debian / Ubuntu (apt)
apt update # refresh package lists
apt upgrade # upgrade installed packages
apt full-upgrade # upgrade + remove obsolete
apt install nginx # install
apt install -y nginx # install (no prompt)
apt remove nginx # remove
apt purge nginx # remove + config files
apt autoremove # remove orphaned packages
apt search nginx # search packages
apt show nginx # package info
apt list --installed # list installed
apt-cache policy nginx # installed vs available version
# RHEL / CentOS / Fedora (dnf / yum)
dnf update # upgrade all
dnf install nginx # install
dnf remove nginx # remove
dnf search nginx # search
dnf info nginx # info
dnf list installed # list installed
yum update # older CentOS/RHEL
# rpm (low-level, RHEL)
rpm -qa # list all installed packages
rpm -qi nginx # package info
rpm -ql nginx # list files in package
rpm -ivh package.rpm # install from file
rpm -e nginx # erase
# Arch Linux (pacman)
pacman -Syu # sync + upgrade
pacman -S nginx # install
pacman -R nginx # remove
pacman -Ss nginx # search
pacman -Qi nginx # package info
# Snap (Ubuntu / cross-distro)
snap install code --classic
snap list
snap refresh
snap remove code
systemd — services
# Service management
systemctl start nginx # start
systemctl stop nginx # stop
systemctl restart nginx # restart
systemctl reload nginx # reload config (no downtime)
systemctl status nginx # status + recent logs
systemctl enable nginx # start on boot
systemctl disable nginx # don't start on boot
systemctl is-active nginx # active | inactive
systemctl is-enabled nginx # enabled | disabled
# List services
systemctl list-units --type=service # active services
systemctl list-units --type=service --all # all services
systemctl list-unit-files --type=service # all + enabled status
# Logs (journald)
journalctl -u nginx # logs for nginx
journalctl -u nginx -f # follow live
journalctl -u nginx --since "1 hour ago"
journalctl -u nginx -n 100 # last 100 lines
journalctl -b # since last boot
journalctl -p err # errors only
journalctl --disk-usage # journal size
# Write a unit file
# /etc/systemd/system/myapp.service
cat > /etc/systemd/system/myapp.service <<EOF
[Unit]
Description=My Application
After=network.target
[Service]
User=www-data
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/node /opt/myapp/server.js
Restart=always
RestartSec=5
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload # reload unit files
systemctl enable --now myapp # enable + start immediately
SSH
# Connect
ssh user@host # basic
ssh -p 2222 user@host # custom port
ssh -i ~/.ssh/id_rsa user@host # specific key
ssh -J bastion user@internal # jump host (ProxyJump)
# Key management
ssh-keygen -t ed25519 -C "email@example.com" # generate key
ssh-copy-id user@host # install public key on server
cat ~/.ssh/id_ed25519.pub # show public key
ssh-add ~/.ssh/id_ed25519 # add to ssh-agent
# ~/.ssh/config
cat >> ~/.ssh/config <<EOF
Host myserver
HostName 192.168.1.100
User alice
Port 22
IdentityFile ~/.ssh/id_ed25519
ServerAliveInterval 60
EOF
ssh myserver # use alias
# Remote commands
ssh user@host "df -h" # run single command
ssh user@host "ls -la /var/www" # run and exit
ssh -T git@github.com # test GitHub key
# File transfer
scp file.txt user@host:/tmp/
scp user@host:/remote/file.txt ./
sftp user@host # interactive SFTP
# Port forwarding
ssh -L 8080:localhost:80 user@host # local:8080 → remote:80
ssh -R 9090:localhost:3000 user@host # remote:9090 → local:3000
ssh -D 1080 user@host # SOCKS proxy
# Server hardening (/etc/ssh/sshd_config)
# PermitRootLogin no
# PasswordAuthentication no
# PubkeyAuthentication yes
# Port 2222
Archives and compression
# tar
tar -czf archive.tar.gz dir/ # create gzip
tar -cjf archive.tar.bz2 dir/ # create bzip2
tar -cJf archive.tar.xz dir/ # create xz (smallest)
tar -xzf archive.tar.gz # extract
tar -xzf archive.tar.gz -C /tmp/ # extract to directory
tar -tzf archive.tar.gz # list contents (no extract)
tar -xzf archive.tar.gz file.txt # extract single file
# gz / bz2 / xz
gzip file.txt # compress → file.txt.gz
gzip -d file.txt.gz # decompress
gunzip file.txt.gz # same as -d
bzip2 file.txt # compress → file.txt.bz2
xz file.txt # compress → file.txt.xz
# zip
zip archive.zip file1.txt file2.txt
zip -r archive.zip dir/
unzip archive.zip
unzip archive.zip -d /tmp/
unzip -l archive.zip # list contents
# Quick cheat: flag meaning
# -c create -x extract -z gzip -j bzip2 -J xz
# -f file -v verbose -t list -C change dir
Shell tricks and productivity
# History
history # command history
history | grep ssh # search history
!42 # run command #42
!! # re-run last command
!ssh # run last command starting with "ssh"
Ctrl+R # reverse search history
# Keyboard shortcuts (bash/zsh)
Ctrl+C # kill current process
Ctrl+Z # suspend process (resume with fg)
Ctrl+D # EOF / logout
Ctrl+L # clear screen
Ctrl+A # beginning of line
Ctrl+E # end of line
Ctrl+W # delete word backward
Alt+F / Alt+B # move forward/back one word
Ctrl+K # kill to end of line
Ctrl+U # kill to beginning of line
Tab # autocomplete
Tab Tab # show all completions
# Redirects
command > file.txt # stdout to file (overwrite)
command >> file.txt # stdout to file (append)
command 2> error.log # stderr to file
command 2>&1 # stderr → stdout
command > /dev/null 2>&1 # discard all output
command < input.txt # stdin from file
# Pipes and subshells
cat file.txt | grep "error" | wc -l # count error lines
ls | sort | head -5 # first 5 sorted entries
echo $(date +%Y-%m-%d) # subshell substitution
mkdir $(date +%F) && cd $_ # mkdir today's date, cd to it
# Variables
NAME="Alice"
echo "Hello, $NAME"
echo "Home: ${HOME}"
unset NAME
export PATH="$PATH:/opt/myapp/bin" # extend PATH permanently → .bashrc
# Aliases (add to ~/.bashrc)
alias ll="ls -la"
alias gs="git status"
alias ..="cd .."
alias ...="cd ../.."
alias grep="grep --color=auto"
# Environment
env # all env variables
printenv HOME # specific variable
export EDITOR=vim # set env var
source ~/.bashrc # reload config
Environment and shell configuration
# Shell config files (bash)
~/.bashrc # interactive non-login shells (most terminals)
~/.bash_profile # login shells (ssh, console login)
~/.bash_logout # run on logout
/etc/bash.bashrc # system-wide bashrc
/etc/profile # system-wide profile
# Common ~/.bashrc additions
export EDITOR=vim
export VISUAL=vim
export HISTSIZE=10000
export HISTFILESIZE=20000
export HISTCONTROL=ignoredups:erasedups
shopt -s histappend
# PATH management
echo $PATH
export PATH="$HOME/.local/bin:$PATH" # prepend
export PATH="$PATH:/opt/custom/bin" # append
# Check which shell
echo $SHELL
echo $0
bash --version
Cron — scheduled tasks
crontab -e # edit cron for current user
crontab -l # list crons
crontab -r # remove all crons
crontab -u alice -l # list crons for user alice (root)
# Cron syntax
# ┌──── minute (0-59)
# │ ┌─── hour (0-23)
# │ │ ┌── day of month (1-31)
# │ │ │ ┌─ month (1-12)
# │ │ │ │ ┌ day of week (0-7, 0=Sun)
# * * * * * command
0 2 * * * /opt/backup.sh # daily at 2:00 AM
*/5 * * * * /opt/check.sh # every 5 minutes
0 9 * * 1 /opt/weekly.sh # Monday 9 AM
0 0 1 * * /opt/monthly.sh # 1st of month midnight
# Cron special strings
@reboot /opt/startup.sh # on boot
@daily /opt/backup.sh # = 0 0 * * *
@weekly /opt/clean.sh # = 0 0 * * 0
@monthly /opt/report.sh # = 0 0 1 * *
# Output / errors
0 2 * * * /opt/backup.sh >> /var/log/backup.log 2>&1
# System cron
ls /etc/cron.d/ # per-app crons (include username field)
ls /etc/cron.daily/ # scripts run daily
ls /etc/cron.hourly/ # scripts run hourly
Common one-liners
# Find and kill process on port 8080
kill $(lsof -ti :8080)
# Count lines in all .py files
find . -name "*.py" -exec wc -l {} + | tail -1
# Disk usage, sorted largest first
du -sh /* 2>/dev/null | sort -rh | head -20
# Extract IP addresses from a log
grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}' access.log | sort | uniq -c | sort -rn
# Monitor a command output every 2 seconds
watch -n 2 "df -h"
# Show 10 largest files
find / -xdev -type f -printf '%s %p\n' 2>/dev/null | sort -rn | head -10
# Replace string in multiple files
find . -type f -name "*.conf" -exec sed -i 's/old/new/g' {} \;
# Show all listening ports with process names
ss -tlnp | awk 'NR>1 {print $4, $6}' | column -t
# Tail multiple log files
tail -f /var/log/nginx/access.log /var/log/nginx/error.log
# Create date-stamped backup
cp important.conf important.conf.$(date +%Y%m%d_%H%M%S).bak
# Check if a port is open
nc -zv 192.168.1.1 22 2>&1
# Base64 encode / decode
echo -n "password" | base64
echo "cGFzc3dvcmQ=" | base64 -d
# Generate random password
openssl rand -base64 16
# Count unique visitors in nginx log
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head
# Find recently modified files
find /var/www -name "*.php" -newer /tmp/reference -type f
# Run a command on multiple servers
for host in web1 web2 web3; do ssh $host "sudo systemctl status nginx"; done
Linux distributions comparison
| Feature | Debian/Ubuntu | RHEL/CentOS | Arch Linux | Alpine |
|---|---|---|---|---|
| Package manager | apt | dnf/yum | pacman | apk |
| Release model | Stable/LTS | Enterprise | Rolling | Rolling |
| Init system | systemd | systemd | systemd | OpenRC |
| Primary use | Servers, desktop | Enterprise servers | Desktop, advanced | Containers |
| Root login SSH | No (default) | No (default) | Config | Config |
| Docker base image | ubuntu:22.04 | ubi9 | archlinux | alpine |
| Container size | ~29 MB | ~210 MB | ~175 MB | ~7 MB |
Common mistakes
| Mistake | Problem | Fix |
|---|---|---|
rm -rf / |
Deletes everything | Always double-check path; use --no-preserve-root awareness |
chmod 777 dir/ |
Anyone can write | Use 755 for dirs, 644 for files |
Editing /etc/sudoers directly |
Syntax error → locked out | Always use visudo |
kill -9 as first choice |
Skips cleanup | Try kill PID (SIGTERM) first |
| Running as root all the time | Security risk | Create regular user, sudo when needed |
usermod -G (without -a) |
Removes existing groups | Always usermod -aG |
crontab -r instead of -e |
Deletes all crons | Confirm before running |
Missing 2>&1 in cron |
Silent errors | Redirect stderr in cron jobs |
Linux vs macOS command differences
| Task | Linux | macOS |
|---|---|---|
| Edit in-place | sed -i 's/a/b/' file |
sed -i '' 's/a/b/' file |
ls colors |
Built-in | Needs --color=auto or alias |
date format |
date +%s (epoch) |
Same |
stat file |
stat -c %s file (size) |
stat -f %z file |
| Open file | xdg-open file |
open file |
| Copy to clipboard | xclip -sel clip |
pbcopy |
| Find process on port | ss -tlnp | grep :80 |
lsof -i :80 |
| Package manager | apt/dnf/pacman | brew |
| Init system | systemd | launchd |
Frequently asked questions
What's the difference between apt and apt-get?
apt is the modern, user-friendly front-end with progress bars and better output. apt-get is the older, stable, scriptable version. Use apt in the terminal, apt-get in scripts (predictable output).
How do I run a command in the background that survives logout?
Three options: nohup command & (basic), screen or tmux (interactive session you can re-attach), or a proper systemd service (production). For one-off tasks, nohup command > output.log 2>&1 & is simplest.
What's the difference between kill and kill -9?
kill PID sends SIGTERM (15) — the process can catch it, clean up, and exit gracefully. kill -9 PID sends SIGKILL — the kernel terminates it immediately with no cleanup. Always try SIGTERM first; use SIGKILL only if the process doesn't respond.
How do I know which process is using a port?
ss -tlnp | grep :80 # shows process name/PID
lsof -i :80 # alternative
fuser 80/tcp # just the PID
What's the safest way to edit system files?
Always make a backup first: cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak. Use visudo for sudoers. For services, test config before restart: nginx -t or systemctl configtest.
How do I make a cron job log its output?
0 2 * * * /opt/backup.sh >> /var/log/backup.log 2>&1
The >> /var/log/backup.log appends stdout; 2>&1 redirects stderr to the same file.