Handy cmd

đź’ˇ
For fold fish minds like mine. Hehhe

File Navigation & Management

bash

# Navigation
pwd                          # Print working directory
cd /path/to/directory       # Change directory
cd ~                        # Go to home directory
cd -                        # Go to previous directory
ls -la                      # List all files (including hidden)
tree                        # Show directory tree

# File Management
cp source dest              # Copy file
mv source dest              # Move/rename file
rm file                     # Remove file
rm -rf directory            # Remove directory recursively
mkdir -p path/to/dir        # Create nested directories
touch file.txt              # Create empty file

# Viewing Files
cat file.txt                # Display entire file
less file.txt               # View file page by page
head -n 20 file.txt         # First 20 lines
tail -n 20 file.txt         # Last 20 lines
tail -f file.log            # Follow file (live updates)

Practice:

bash

# Exercise 1: Create directory structure
mkdir -p ~/practice/{dir1,dir2,dir3}
cd ~/practice
touch dir1/file{1..10}.txt

# Exercise 2: Find and count
find . -name "*.txt" | wc -l

# Exercise 3: View logs
sudo tail -f /var/log/syslog

Text Processing Commands

bash

# grep - Search text
grep "error" logfile.txt
grep -i "error" file.txt              # Case insensitive
grep -r "error" /var/log/             # Recursive search
grep -v "info" file.txt               # Inverse (exclude)
grep -A 5 "error" file.txt            # 5 lines after match
grep -B 5 "error" file.txt            # 5 lines before match

# awk - Pattern scanning & processing
awk '{print $1}' file.txt             # Print first column
awk -F: '{print $1,$3}' /etc/passwd   # Custom delimiter
awk '$3 > 1000' /etc/passwd           # Conditional

# sed - Stream editor
sed 's/old/new/' file.txt             # Replace first occurrence
sed 's/old/new/g' file.txt            # Replace all
sed -i 's/old/new/g' file.txt         # Edit in place
sed -n '10,20p' file.txt              # Print lines 10-20

# cut - Extract columns
cut -d: -f1 /etc/passwd               # First field
cut -c1-10 file.txt                   # First 10 characters

# sort & uniq
sort file.txt                         # Sort lines
sort -n file.txt                      # Numeric sort
sort -r file.txt                      # Reverse sort
uniq file.txt                         # Remove duplicates
sort file.txt | uniq -c               # Count occurrences

# wc - Word count
wc -l file.txt                        # Count lines
wc -w file.txt                        # Count words
wc -c file.txt                        # Count bytes
# Q1: Find top 10 IPs in access log
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10

# Q2: Find all files modified in last 24 hours
find /var/log -type f -mtime -1

# Q3: Count ERROR lines in log
grep -c "ERROR" application.log

# Q4: Extract email addresses from file
grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" file.txt

I/O Redirection

bash

# Standard streams:
# 0 = stdin (input)
# 1 = stdout (output)
# 2 = stderr (error output)

# Basic redirection
command > file.txt                    # Redirect stdout to file (overwrite)
command >> file.txt                   # Redirect stdout to file (append)
command 2> error.log                  # Redirect stderr to file
command > output.txt 2> error.log     # Separate stdout and stderr
command &> all.log                    # Both stdout and stderr to same file
command 2>&1                          # Redirect stderr to stdout

# Pipes (|)
command1 | command2                   # Output of cmd1 → input of cmd2
cat file.txt | grep "error" | wc -l

# Here documents
cat << EOF > file.txt
Line 1
Line 2
EOF

# Input redirection
command < input.txt                   # Read from file

# Examples
ls -la > listing.txt                  # Save directory listing
ps aux | grep nginx | grep -v grep    # Find nginx process
find / -name "*.log" 2>/dev/null      # Suppress error messages
# Exercise 1: Extract unique usernames from auth.log
sudo grep "Failed password" /var/log/auth.log | awk '{print $9}' | sort -u

# Exercise 2: Monitor live errors in log
tail -f /var/log/syslog | grep --line-buffered "error"

# Exercise 3: Create report
{
  echo "System Report - $(date)"
  echo "Disk Usage:"
  df -h
  echo "Memory Usage:"
  free -h
  echo "Top 5 Processes:"
  ps aux --sort=-%mem | head -6
} > system_report.txt

System Administration

User & Group Management

# User Management
useradd username                      # Create user
useradd -m -s /bin/bash username      # Create with home dir and shell
usermod -aG sudo username             # Add user to sudo group
userdel username                      # Delete user
userdel -r username                   # Delete user and home directory
passwd username                       # Set/change password
id username                           # Show user info
whoami                                # Current user
w                                     # Who is logged in

# Group Management
groupadd groupname                    # Create group
groupdel groupname                    # Delete group
groups username                       # Show user's groups
gpasswd -a username groupname         # Add user to group
gpasswd -d username groupname         # Remove user from group

# Important Files
/etc/passwd                           # User account info
/etc/shadow                           # Encrypted passwords
/etc/group                            # Group info

Process & Memory Management

# Process Management
ps aux                                # All processes
ps aux | grep nginx                   # Find specific process
top                                   # Interactive process viewer
htop                                  # Better top (if installed)
pstree                                # Process tree
pgrep -u username                     # Find processes by user

kill PID                              # Terminate process (SIGTERM)
kill -9 PID                           # Force kill (SIGKILL)
killall processname                   # Kill by name
pkill -u username                     # Kill all user processes

# Background/foreground
command &                             # Run in background
jobs                                  # List background jobs
fg %1                                 # Bring job 1 to foreground
bg %1                                 # Resume job 1 in background
Ctrl+Z                                # Suspend current process

# Priority
nice -n 10 command                    # Run with priority
renice -n 5 -p PID                    # Change priority

# Memory Management
free -h                               # Memory usage
vmstat 1 5                            # Virtual memory stats
cat /proc/meminfo                     # Detailed memory info

"Server is slow, how do you identify the problematic process?"

#
top                                   # Check CPU/memory usage
# Press 'M' to sort by memory
# Press 'P' to sort by CPU
ps aux --sort=-%mem | head -10        # Top memory consumers
ps aux --sort=-%cpu | head -10        # Top CPU consumers

Disk Usage

# Disk space
df -h                                 # Filesystem usage
df -i                                 # Inode usage (remember this!)
du -sh /path                          # Directory size
du -sh /* | sort -h                   # Size of all root directories

# Find large files
find / -type f -size +100M 2>/dev/null
du -ah /var | sort -rh | head -20     # Top 20 largest

# Disk I/O
iostat -x 1 5                         # I/O statistics
iotop                                 # I/O by process (like top for I/O)
# Find what's consuming disk space
sudo du -sh /var/* | sort -h | tail -10
sudo find /var/log -name "*.log" -size +100M -exec ls -lh {} \;

Service Management

# systemd (Modern Linux)
systemctl start service               # Start service
systemctl stop service                # Stop service
systemctl restart service             # Restart service
systemctl reload service              # Reload config
systemctl status service              # Check status
systemctl enable service              # Enable on boot
systemctl disable service             # Disable on boot
systemctl list-units --type=service   # List all services
systemctl list-units --failed         # Failed services

# Logs
journalctl                            # All logs
journalctl -u nginx                   # Service-specific logs
journalctl -f                         # Follow logs (like tail -f)
journalctl -n 50                      # Last 50 lines
journalctl --since "1 hour ago"       # Time-based filtering
journalctl -p err                     # Error priority only

Handling Logs

# Log locations
/var/log/syslog                       # General system logs (Debian/Ubuntu)
/var/log/messages                     # General system logs (RHEL/CentOS)
/var/log/auth.log                     # Authentication logs
/var/log/kern.log                     # Kernel logs
/var/log/apache2/                     # Apache logs
/var/log/nginx/                       # Nginx logs

# Viewing logs
tail -f /var/log/syslog               # Follow log
tail -100 /var/log/syslog             # Last 100 lines
less /var/log/syslog                  # Page through log
zless /var/log/syslog.1.gz            # View compressed log

# Searching logs
grep "error" /var/log/syslog
grep -i "failed" /var/log/auth.log
journalctl -u nginx | grep "error"

# Log rotation
/etc/logrotate.conf                   # Configuration
/etc/logrotate.d/                     # Service-specific configs

"Application is throwing errors. How do you investigate?"

# :
# 1. Check if service is running
systemctl status myapp

# 2. Check recent logs
journalctl -u myapp -n 100
# Or
tail -100 /var/log/myapp/error.log

# 3. Follow logs in real-time
journalctl -u myapp -f

# 4. Check for patterns
journalctl -u myapp | grep -i "error\|exception\|failed"

# 5. Check system resources
top
df -h
free -h

IPtables

iptables is the kernel-level packet filtering system. It organizes rules into tables (filter, nat, mangle), each with chains like INPUT, OUTPUT, FORWARD. Each chain contains ordered rules that inspect packet properties and decide whether to ACCEPT, DROP, or modify.

It can filter packets (firewalling) or rewrite addresses (NAT)

Example scenario 1 — Allow web traffic

# Allow inbound HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Drop everything else
iptables -P INPUT DROP

Now only ports 80/443 respond — classic production firewall behavior.

Example scenario 2 — NAT (masquerading)

You’re running a router that connects private subnet 10.0.0.0/24 to the internet.

# Replace eth0 with your public interface
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

That means:

“Rewrite all outgoing packets’ source IP to my public IP, so replies come back correctly.”

That’s how home routers let many devices share one public IP.

Example scenario 3 — Mangle: Adjust packet TTL

iptables -t mangle -A PREROUTING -i eth0 -j TTL --ttl-inc 1

This increments TTL by 1 for all incoming packets.
Rarely needed, but powerful for packet manipulation.

Read more