Linux Classroom notes 01/June/2026

1. Basic Commands

ls                      # List files
ls -l                   # Long format
ls -a                   # Show hidden files
ls -lh                  # Human-readable sizes
ls -lt                  # Sort by modified time

pwd                     # Print working directory
cd /path/to/dir         # Change directory
cd ..                   # Go up one level
cd ~                    # Go to home directory
cd -                    # Go to previous directory

mkdir dirname           # Create directory
mkdir -p parent/child   # Create nested directories

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

cp file.txt /tmp/           # Copy file
cp -r dir/ /tmp/            # Copy directory recursively
cp -p file.txt backup.txt   # Preserve timestamps/perms

mv file.txt newname.txt     # Rename file
mv file.txt /tmp/           # Move file

rm file.txt             # Remove file
rm -f file.txt          # Force remove (no prompt)
rm -r dir/              # Remove directory recursively
rm -rf dir/             # Force remove directory

echo "text"             # Print to terminal
echo "text" > file.txt  # Write/overwrite to file
echo "text" >> file.txt # Append to file

cat file.txt            # Display file
cat file1 file2         # Concatenate files

ln -s /path/target link # Create symbolic link
ln file.txt hardlink    # Create hard link

clear                   # Clear terminal
history                 # Show command history
history | grep ssh      # Search history
!100                    # Re-run command #100
!!                      # Re-run last command

alias ll='ls -lah'      # Create alias
unalias ll              # Remove alias

man ls                  # Manual page for command
which nginx             # Location of command
whereis nginx           # Locate binary + man page
type ls                 # Show command type

2. File Viewing & Editing

cat file.txt                # Print entire file
less file.txt               # Paginate (q=quit, /=search)
more file.txt               # Paginate (older)

head file.txt               # First 10 lines
head -n 20 file.txt         # First 20 lines
head -c 50 file.txt         # First 50 bytes
head -n -5 file.txt         # All except last 5 lines

tail file.txt               # Last 10 lines
tail -n 50 file.txt         # Last 50 lines
tail -c 100 file.txt        # Last 100 bytes
tail -f /var/log/syslog     # Follow live (log monitoring)
tail -F /var/log/app.log    # Follow + retry if file recreated
tail -f file1 file2         # Follow multiple files

wc -l file.txt              # Count lines
wc -w file.txt              # Count words
wc -c file.txt              # Count bytes

nano file.txt               # Simple editor (Ctrl+O save, Ctrl+X exit)
vim file.txt                # Advanced editor
# vim: i=insert, Esc=normal, :wq=save+quit, :q!=quit without save
# vim: dd=delete line, yy=copy line, p=paste, /=search

diff file1.txt file2.txt    # Compare two files
diff -u file1 file2         # Unified diff format

3. Search & Filter

# grep — Search in files
grep "error" app.log
grep -i "error" app.log         # Case-insensitive
grep -r "config" /etc/          # Recursive search
grep -n "error" app.log         # Show line numbers
grep -v "debug" app.log         # Invert match (exclude)
grep -c "error" app.log         # Count matching lines
grep -l "error" *.log           # Show filenames only
grep -A 3 "error" app.log       # 3 lines After match
grep -B 3 "error" app.log       # 3 lines Before match
grep -E "error|warn" app.log    # Extended regex (OR)
grep -w "error" app.log         # Whole word match

# find — Locate files/dirs
find . -name "file.txt"
find /var/log -type f -name "*.log"
find /path -type d -name "config"   # Directories only
find /path -mtime -7                # Modified last 7 days
find /path -mtime +30               # Older than 30 days
find /path -size +100M              # Larger than 100MB
find /path -size -1k                # Smaller than 1KB
find /path -name "*.tmp" -delete    # Find and delete
find /path -name "*.sh" -exec chmod +x {} \;  # Find + exec
find /path -perm 644                # By permission
find /path -empty                   # Empty files
find /path -user root               # By owner
find . -name "*.log" | xargs rm     # Pipe to xargs

# locate — Fast indexed search
sudo apt install plocate -y
locate filename
sudo updatedb                   # Refresh index

4. Text Processing

AWK

awk '{print $1}' file.txt               # Print column 1
awk '{print $1, $3}' file.txt           # Multiple columns
awk -F',' '{print $1, $2}' file.csv    # CSV delimiter
awk -F':' '{print $1, $7}' /etc/passwd # Parse /etc/passwd
awk '/error/ {print}' file.log          # Pattern match
awk '{print NR, $0}' file.txt           # With line numbers
awk 'END {print NR}' file.txt           # Total line count
awk '{print NF}' file.txt               # Number of fields per line
awk '{print $NF}' file.txt              # Print last field
awk '{sum += $2} END {print sum}' file  # Sum column 2
awk '$3 > 100 {print}' file.txt         # Conditional filter
awk '!seen[$1]++' file.txt              # Remove duplicates
awk '{gsub(/foo/, "bar"); print}' file  # Replace text
awk 'NF > 5 {print}' file.txt           # Lines with >5 fields
awk '/START/,/END/ {print}' file.txt    # Print between patterns
awk 'BEGIN{print "START"} {print} END{print "END"}' file

sed

sed 's/old/new/' file.txt           # Replace first occurrence per line
sed 's/old/new/g' file.txt          # Replace all occurrences
sed 's/old/new/gi' file.txt         # Case-insensitive replace
sed -i 's/old/new/g' file.txt       # In-place edit
sed -n '5,10p' file.txt             # Print lines 5-10
sed '3d' file.txt                   # Delete line 3
sed '/pattern/d' file.txt           # Delete matching lines
sed -n '/error/p' file.txt          # Print only matching lines
sed 's/^/# /' file.txt              # Add # at start of each line
sed 's/ *$//' file.txt              # Remove trailing spaces
sed '/^$/d' file.txt                # Remove empty lines

sort, uniq, tr

sort file.txt               # Alphabetical
sort -r file.txt            # Reverse
sort -n file.txt            # Numeric
sort -k2 file.txt           # By column 2
sort -t',' -k3 -n file.csv  # CSV column 3 numeric
sort -u file.txt            # Sort + remove duplicates
sort -h sizes.txt           # Human-readable (1K, 2M)

uniq file.txt               # Remove consecutive duplicates
uniq -c file.txt            # Count occurrences
uniq -d file.txt            # Show duplicate lines only
uniq -u file.txt            # Show unique lines only
sort file.txt | uniq -c | sort -rn   # Full frequency count

tr 'a-z' 'A-Z' < file.txt   # Lowercase → uppercase
tr -d '0-9' < file.txt       # Delete digits
tr -s ' ' < file.txt         # Squeeze repeated spaces
tr ':' '\n' < file.txt       # Replace colons with newlines
tr -d '\n' < file.txt        # Remove all newlines

cut -d',' -f1 file.csv       # Extract column 1 (CSV)
cut -d':' -f1,7 /etc/passwd  # Extract fields 1 and 7
cut -c1-10 file.txt          # Extract characters 1-10

paste file1.txt file2.txt    # Merge files side by side
paste -d',' file1 file2      # Merge with comma delimiter

5. User & Group Management

whoami                              # Current username
id                                  # UID, GID, groups
id username                         # Specific user info
who                                 # Logged-in users
w                                   # Who + what they're doing
last                                # Login history
lastlog                             # Last login per user

# Create / delete users
sudo useradd -m -s /bin/bash user1      # Create with home + bash
sudo useradd -m -d /opt/tomcat -U -s /bin/false tomcat  # Service user
sudo adduser user2                      # Interactive create
sudo userdel user1                      # Delete user
sudo userdel -r user1                   # Delete + remove home dir

# Password
passwd                          # Change own password
sudo passwd user1               # Change user's password
sudo passwd -e user1            # Expire password (force reset)
sudo passwd -l user1            # Lock account
sudo passwd -u user1            # Unlock account

# Modify user
sudo usermod -aG sudo user1         # Add to sudo group
sudo usermod -aG docker user1       # Add to docker group
sudo usermod -s /bin/bash user1     # Change shell
sudo usermod -d /new/home user1     # Change home dir
sudo usermod -l newname oldname     # Rename user

# Groups
sudo groupadd developers            # Create group
sudo groupdel developers            # Delete group
sudo gpasswd -a user1 developers    # Add user to group
sudo gpasswd -d user1 developers    # Remove user from group
groups user1                        # Show user's groups
cat /etc/group                      # List all groups
cat /etc/passwd                     # List all users

# Switch users
su - user1                          # Switch to user1
sudo -i                             # Switch to root
sudo su -                           # Root shell
sudo -l                             # List sudo permissions

6. File Permissions

ls -l                       # View permissions

# chmod — numeric
chmod 755 file              # rwxr-xr-x
chmod 644 file              # rw-r--r--
chmod 600 file              # rw------- (SSH keys)
chmod 700 dir               # rwx------ (private)
chmod -R 755 /dir           # Recursive

# chmod — symbolic
chmod u+x file              # Add execute for owner
chmod g+w file              # Add write for group
chmod o-r file              # Remove read from others
chmod a+x file              # Add execute for all
chmod u=rwx,go=rx file      # Set exact permissions

# chown / chgrp
chown user file             # Change owner
chown user:group file       # Change owner + group
chown -R user:group /dir    # Recursive
chgrp group file            # Change group only

# umask
umask                       # View current (default 022)
umask 022                   # Files=644, Dirs=755
umask 027                   # Files=640, Dirs=750

# Special bits
chmod u+s file              # SUID — run as file owner
chmod g+s dir               # SGID — inherit group
chmod +t dir                # Sticky bit — only owner deletes

# Permission table
# 7=rwx  6=rw-  5=r-x  4=r--  0=---

7. Process Management

ps aux                      # All running processes
ps aux | grep nginx         # Filter by name
ps -ef                      # Full format listing
ps -ef --forest             # Process tree format
pgrep nginx                 # Get PID by name
pidof nginx                 # PID of named process
pstree                      # Visual process tree

top                         # Live process monitor (q to quit)
htop                        # Enhanced monitor (if installed)

kill 1234                   # Graceful stop (SIGTERM)
kill -9 1234                # Force kill (SIGKILL)
kill -15 1234               # Explicit SIGTERM
kill -l                     # List all signals
killall nginx               # Kill all by name
pkill -f "python script.py" # Kill by full command
pkill -u username           # Kill all user's processes

# Job control
command &                   # Run in background
jobs                        # List background jobs
fg                          # Bring last job to foreground
fg %2                       # Bring job #2 to foreground
bg                          # Resume job in background
Ctrl+Z                      # Suspend foreground process
Ctrl+C                      # Terminate foreground process
nohup command &             # Run, persist after logout
nohup ./script.sh > out.log 2>&1 &   # With output redirect
disown %1                   # Detach job from shell
screen                      # Terminal multiplexer (persistent)
tmux                        # Modern terminal multiplexer

8. System Info & Monitoring

uname -a                    # Kernel + system info
uname -r                    # Kernel version only
hostname                    # Hostname
hostnamectl                 # Full hostname info
hostnamectl set-hostname newname  # Change hostname
lscpu                       # CPU info
lsmem                       # Memory info
lshw                        # Full hardware info
lsblk                       # Block devices (disks)
lsusb                       # USB devices
lspci                       # PCI devices

uptime                      # Uptime + load average
last reboot                 # Reboot history

free -h                     # Memory usage (human-readable)
vmstat 1 5                  # Virtual memory stats (5 samples)
iostat                      # CPU + I/O stats
iostat -x 1                 # Extended I/O stats every 1s
mpstat                      # Per-CPU stats
sar -u 1 3                  # CPU usage over time
sar -r 1 3                  # Memory over time

top                         # Live processes
htop                        # Enhanced live view

ulimit -a                   # Show all resource limits
ulimit -n 65535             # Set max open file descriptors

cat /proc/cpuinfo           # CPU details
cat /proc/meminfo           # Memory details
cat /proc/version           # Kernel version
cat /etc/os-release         # OS version info
cat /etc/hostname           # Hostname file

# Logs
dmesg                       # Kernel ring buffer
dmesg | tail -20            # Last 20 kernel messages
journalctl                  # systemd journal
journalctl -f               # Follow live logs
journalctl -n 100           # Last 100 entries
journalctl --since "1 hour ago"
journalctl -u nginx         # Logs for specific service
journalctl -p err           # Error-level only

9. Disk & Storage

df -h                       # Disk space (all filesystems)
df -h /                     # Root filesystem only
df -i                       # Inode usage

du -sh /var/log             # Directory total size
du -sh *                    # Size of each item in current dir
du -h --max-depth=1 /var    # One level deep
du -sh /path | sort -h      # Sort by size

lsblk                       # List block devices
lsblk -f                    # With filesystem info
blkid                       # Block device UUIDs
fdisk -l                    # Disk partition info (root)
parted -l                   # Partition tool

mount                       # Show all mounts
mount /dev/sdb1 /mnt/data   # Mount device
umount /mnt/data            # Unmount
cat /etc/fstab              # Permanent mounts config

# Check for reboot after patch
cat /var/run/reboot-required
cat /var/run/reboot-required.pkgs

10. Networking

# Connectivity
ping google.com
ping -c 4 8.8.8.8           # Send 4 packets
ping -i 2 google.com        # 2 second interval
traceroute google.com       # Trace route
mtr google.com              # Interactive traceroute

# DNS
nslookup google.com
dig google.com
dig google.com +short       # IP only
dig google.com MX           # Mail records
dig @8.8.8.8 google.com     # Use specific DNS server
host google.com

# IP / Interface
ip a                        # All interfaces + IPs
ip addr show eth0           # Specific interface
ip link show                # Link state
ip route show               # Routing table
ip route add default via 192.168.1.1  # Add default gateway
ip link set eth0 up/down    # Enable/disable interface

ifconfig                    # Interfaces (older)
ifconfig eth0 up/down

# Public/local IP
curl ifconfig.me            # Public IP
curl -s ifconfig.me
hostname -I                 # All local IPs

# Ports & connections
ss -tuln                    # Listening TCP/UDP ports
ss -tulnp                   # With process name/PID
ss -s                       # Summary
netstat -tuln               # Listening ports (older)
netstat -anp                # All connections + PID
lsof -i :80                 # Process using port 80
lsof -i :8080
lsof -i TCP                 # All TCP connections

# Port scanning
nmap localhost
nmap -sV 192.168.1.1        # Version detection
nmap -p 22,80,443 host      # Specific ports

# HTTP
curl -O https://example.com/file.zip        # Download (keep name)
curl -o out.zip https://example.com/file.zip
curl -I https://example.com                 # Headers only
curl -v https://example.com                 # Verbose
curl -L https://example.com                 # Follow redirects
curl -X POST -d "key=val" https://api.example.com
curl -H "Authorization: Bearer TOKEN" https://api.example.com
curl -u user:pass https://example.com       # Basic auth

wget https://example.com/file.zip
wget -c https://example.com/large.iso      # Resume download
wget -r https://example.com/               # Recursive
wget -q https://example.com/file.zip       # Quiet mode
wget -P /tmp/ https://example.com/file.zip # Save to dir

11. SSH & Remote Access

ssh user@host                           # Connect
ssh -p 2222 user@host                   # Custom port
ssh -i ~/.ssh/id_rsa user@host          # With key file
ssh -v user@host                        # Verbose (debug)
ssh -X user@host                        # X11 forwarding (GUI)
ssh -L 8080:localhost:80 user@host      # Local port forward
ssh -R 9090:localhost:3000 user@host    # Remote port forward
ssh -N -L 3306:db-host:3306 user@jump  # SSH tunnel (no shell)

# Key management
ssh-keygen -t rsa -b 4096               # Generate RSA key
ssh-keygen -t ed25519                   # Generate Ed25519 key (modern)
ssh-copy-id user@host                   # Copy public key to remote
cat ~/.ssh/id_rsa.pub                   # View public key
ssh-add ~/.ssh/id_rsa                   # Add key to agent
ssh-agent bash                          # Start SSH agent

# Config file (~/.ssh/config)
# Host myserver
#   HostName 192.168.1.10
#   User ubuntu
#   IdentityFile ~/.ssh/id_rsa
#   Port 22

# Known hosts
cat ~/.ssh/known_hosts
ssh-keyscan host >> ~/.ssh/known_hosts  # Add host key

# Authorized keys (on remote server)
cat ~/.ssh/authorized_keys

12. SCP & SFTP

# SCP — Secure Copy
scp file.txt user@host:/home/user/              # Local → Remote
scp user@host:/home/user/file.txt /local/path/  # Remote → Local
scp -r /local/dir/ user@host:/remote/dir/       # Directory
scp -P 2222 file.txt user@host:/home/user/      # Custom port
scp -i ~/.ssh/id_rsa file.txt user@host:/tmp/   # With key
scp -p file.txt user@host:/tmp/                 # Preserve timestamps
scp -l 500 largefile.tar.gz user@host:/tmp/     # Limit bandwidth
scp user1@server1:/path/file user2@server2:/path/  # Server to server

# SFTP — Interactive
sftp user@host
sftp -P 2222 user@host
sftp -i ~/.ssh/id_rsa user@host

# SFTP session commands
ls / lls                    # Remote / local listing
cd /path / lcd /path        # Remote / local cd
put file.txt                # Upload file
put -r local_dir/           # Upload directory
get remote.txt              # Download file
get -r remote_dir/          # Download directory
pwd / lpwd                  # Remote / local path
mkdir newfolder             # Create remote dir
rm remotefile.txt           # Delete remote file
rename old.txt new.txt      # Rename remote file
exit                        # Quit SFTP

13. Firewall (UFW / iptables)

# UFW — Uncomplicated Firewall (Ubuntu)
ufw status                  # Show status + rules
ufw status verbose          # Detailed status
ufw enable                  # Enable firewall
ufw disable                 # Disable firewall
ufw allow 22                # Allow SSH
ufw allow 80/tcp            # Allow HTTP
ufw allow 443/tcp           # Allow HTTPS
ufw allow 8080/tcp          # Allow custom port
ufw deny 3306               # Block MySQL
ufw deny from 192.168.1.5   # Block IP
ufw allow from 10.0.0.0/8   # Allow subnet
ufw delete allow 80         # Remove rule
ufw reset                   # Reset all rules
ufw reload                  # Reload rules

# iptables (lower level)
iptables -L                 # List all rules
iptables -L -v -n           # Verbose + numeric
iptables -F                 # Flush (clear all rules)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT   # Allow SSH
iptables -A INPUT -p tcp --dport 80 -j ACCEPT   # Allow HTTP
iptables -A INPUT -j DROP   # Drop everything else
iptables-save               # Save current rules
iptables-restore < rules    # Restore rules

14. Archive & Compression

# tar
tar -czvf archive.tar.gz folder/            # Create .tar.gz
tar -xzvf archive.tar.gz                    # Extract .tar.gz
tar -cjvf archive.tar.bz2 folder/           # Create .tar.bz2
tar -xjvf archive.tar.bz2                   # Extract .tar.bz2
tar -tvf archive.tar.gz                     # List contents
tar -xzvf archive.tar.gz -C /target/dir/   # Extract to dir
tar -czvf out.tar.gz --exclude='*.log' dir/ # Exclude files
tar -xzvf archive.tar.gz specificfile       # Extract one file

# zip / unzip
zip -r archive.zip folder/          # Zip folder
zip archive.zip file1 file2         # Zip specific files
zip -e archive.zip folder/          # Password-protected
zip -9 -r archive.zip folder/       # Max compression (1-9)
unzip archive.zip                   # Extract
unzip archive.zip -d /target/dir/   # Extract to dir
unzip -l archive.zip                # List contents
unzip -o archive.zip                # Overwrite without prompt
unzip -n archive.zip                # Never overwrite

# gzip / bzip2
gzip file.txt               # Compress → file.txt.gz
gzip -d file.txt.gz         # Decompress
gunzip file.txt.gz          # Same as gzip -d
gzip -k file.txt            # Keep original
bzip2 file.txt              # Compress → file.txt.bz2
bunzip2 file.txt.bz2        # Decompress

15. Date & Time

date                                    # Current date + time
date +"%Y-%m-%d"                        # 2026-05-30
date +"%H:%M:%S"                        # 14:30:00
date +"%d/%m/%Y %T"                     # 30/05/2026 14:30:00
date +"%A, %B %d %Y"                    # Saturday, May 30 2026
date +"%s"                              # Unix timestamp
date -d "2 days ago"                    # Past date
date -d "next Monday"                   # Future date
date -d "@1700000000"                   # Convert timestamp
date -s "2026-05-30 14:00:00"           # Set date/time (root)

timedatectl                             # Full time/timezone info
timedatectl set-timezone Asia/Kolkata   # Set timezone
timedatectl set-timezone UTC            # Set to UTC
timedatectl list-timezones              # All timezones
timedatectl list-timezones | grep India

hwclock                     # Hardware clock time
hwclock --systohc           # Sync hardware from system
hwclock --hctosys           # Sync system from hardware

cal                         # Current month calendar
cal 2026                    # Full year calendar
cal 5 2026                  # Specific month/year
uptime                      # Uptime + load average

16. Package Management

APT (Ubuntu / Debian)

sudo apt update                         # Refresh package index
sudo apt upgrade -y                     # Upgrade all packages
sudo apt full-upgrade -y                # Upgrade + handle deps
sudo apt install nginx -y               # Install package
sudo apt install --only-upgrade curl    # Upgrade specific package
sudo apt remove nginx                   # Remove package
sudo apt purge nginx                    # Remove + config files
sudo apt autoremove -y                  # Remove unused deps
sudo apt autoclean                      # Clean cache
sudo apt search nginx                   # Search packages
sudo apt show nginx                     # Package info
apt list --installed                    # List installed
apt list --upgradable                   # List upgradable
sudo dpkg -i package.deb                # Install .deb file
dpkg -l | grep nginx                    # Check if installed

YUM / DNF (RHEL / CentOS)

sudo yum update -y                      # Update all
sudo yum install nginx -y              # Install
sudo yum remove nginx                  # Remove
sudo yum search nginx                  # Search
sudo yum info nginx                    # Package info
sudo yum list installed                # List installed
sudo dnf update -y                     # DNF (CentOS 8+)
sudo dnf install nginx -y
sudo dnf remove nginx
sudo rpm -ivh package.rpm              # Install .rpm file

17. Shell Scripting

Variables & Types

#!/bin/bash

name="devops"                   # String variable
age=30                          # Integer
pi=3.14

fruits=("apple" "banana" "orange")   # Array
echo ${fruits[0]}                     # Access element
echo ${fruits[@]}                     # All elements
echo ${#fruits[@]}                    # Array length

readonly MY_VAR="constant"      # Read-only variable
export PATH=$PATH:/new/path     # Export to child processes

# Special variables
echo $0      # Script name
echo $1 $2   # Arguments 1, 2
echo $@      # All arguments
echo $#      # Number of arguments
echo $$      # Script PID
echo $?      # Exit status of last command
echo $!      # PID of last background job

Conditionals

# if / elif / else
if [ $num -gt 10 ]; then
  echo "Greater"
elif [ $num -eq 10 ]; then
  echo "Equal"
else
  echo "Less"
fi

# File tests
if [ -f file.txt ]; then echo "File exists"; fi
if [ -d /var/log ]; then echo "Dir exists"; fi
if [ -z "$var" ]; then echo "Empty string"; fi
if [ -n "$var" ]; then echo "Non-empty"; fi
if [ -r file ]; then echo "Readable"; fi
if [ -w file ]; then echo "Writable"; fi
if [ -x file ]; then echo "Executable"; fi

# Operators
# -eq -ne -lt -gt -le -ge  (numeric)
# =  !=  <  >              (string)
# && ||  (AND / OR)

Loops

# for loop
for i in 1 2 3 4 5; do
  echo "Number: $i"
done

# for range
for i in {1..10}; do echo $i; done

# for with command
for file in $(ls /tmp/*.log); do
  echo "Processing: $file"
done

# C-style for
for ((i=0; i<5; i++)); do
  echo $i
done

# while loop
count=1
while [ $count -le 5 ]; do
  echo "Count: $count"
  ((count++))
done

# until loop
until [ $count -gt 5 ]; do
  echo $count
  ((count++))
done

# case statement
case $input in
  "start")  echo "Starting..." ;;
  "stop")   echo "Stopping..." ;;
  "status") systemctl status nginx ;;
  *)        echo "Unknown option" ;;
esac

Functions

# Define and call
greet() {
  echo "Hello, $1!"
}
greet "DevOps"

# With local variable + return
add() {
  local result=$(( $1 + $2 ))
  echo $result
}
sum=$(add 4 6)
echo "Sum: $sum"

# Check exit status
if ! command -v docker &>/dev/null; then
  echo "Docker not installed"
  exit 1
fi

Useful Patterns

set -e                      # Exit on any error
set -x                      # Debug — print each command
set -eo pipefail            # Exit on pipe failure too

# Read input
read -p "Enter username: " username
read -sp "Enter password: " password   # Silent (no echo)

# String operations
str="hello world"
echo ${str^^}               # Uppercase
echo ${str,,}               # Lowercase
echo ${#str}                # Length
echo ${str/world/linux}     # Replace

# Arithmetic
result=$((5 + 3))
result=$(expr 5 + 3)
let result=5+3

18. Cron Jobs

crontab -e          # Edit crontab
crontab -l          # List crontabs
crontab -r          # Remove all crontabs
crontab -u user -l  # List for specific user
sudo crontab -e     # Root crontab

# Cron format:
# MIN  HOUR  DOM  MON  DOW  COMMAND
#  0     2    *    *    0   /path/script.sh

# Examples
* * * * * /root/script.sh              # Every minute
0 * * * * /root/script.sh              # Every hour
0 2 * * * /root/script.sh              # Daily at 2 AM
0 2 * * 0 /root/script.sh              # Every Sunday 2 AM
0 2 1 * * /root/script.sh              # 1st of every month
*/5 * * * * /root/script.sh            # Every 5 minutes
0 8,17 * * * /root/script.sh           # 8 AM and 5 PM
0 9 * * 1-5 /root/script.sh            # Weekdays at 9 AM

# With logging
* * * * * /root/script.sh >> /var/log/cron.log 2>&1

# Special strings
@reboot /root/script.sh                # Run at boot
@daily /root/backup.sh                 # Daily
@weekly /root/cleanup.sh               # Weekly

# Reference: https://crontab.guru/

19. systemd Service Management

# Status & Control
systemctl status nginx
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx          # Reload config (no downtime)
systemctl enable nginx          # Auto-start on boot
systemctl disable nginx         # Remove from boot
systemctl is-active nginx       # Check if running
systemctl is-enabled nginx      # Check if enabled
systemctl daemon-reload         # Reload unit files (after editing)

# Listing
systemctl list-units --type=service         # All active services
systemctl list-units --type=service --all   # Including inactive
systemctl list-unit-files                   # All unit files

# Logs
journalctl -u nginx                     # All logs for service
journalctl -u nginx -f                  # Follow live
journalctl -u nginx -n 100              # Last 100 lines
journalctl -u nginx --since "1 hour ago"
journalctl -u nginx --since "2026-05-30 08:00"
journalctl -n 50 -p err                 # Last 50 errors
journalctl -b                           # Since last boot
journalctl --disk-usage                 # Journal disk usage

# Service file location
# /etc/systemd/system/myapp.service
# /usr/lib/systemd/system/myapp.service

# Minimal service file template
cat > /etc/systemd/system/myapp.service << 'EOF'
[Unit]
Description=My Application
After=network.target

[Service]
Type=simple
User=appuser
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/java -jar /opt/myapp/app.jar
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable myapp
sudo systemctl start myapp

20. Maven Commands

# Install
sudo apt install maven -y
mvn --version

# Core lifecycle
mvn clean                           # Delete target/
mvn validate                        # Validate pom.xml
mvn compile                         # Compile source
mvn test                            # Run unit tests
mvn package                         # Create .jar/.war
mvn verify                          # Run integration tests
mvn install                         # Install to local ~/.m2
mvn deploy                          # Publish to remote repo

# Common combinations
mvn clean package                   # Clean + package
mvn clean install                   # Most common CI command
mvn clean install -DskipTests       # Skip test execution
mvn clean install -Dmaven.test.skip=true  # Skip test compile too
mvn clean package -Dmaven.test.failure.ignore=true

# Dependencies
mvn dependency:tree                 # Full dependency tree
mvn dependency:resolve              # Resolve + list deps
mvn dependency:purge-local-repository  # Clear local cache

# Debugging / info
mvn help:effective-pom              # Show resolved POM
mvn help:effective-settings         # Show settings
mvn help:describe -Dplugin=compiler # Plugin info
mvn versions:display-dependency-updates  # Available updates
mvn site                            # Generate project docs
mvn clean install -X                # Debug mode
mvn clean install -o                # Offline mode
mvn -pl module-name clean package   # Specific submodule
mvn -am -pl module-name package     # With dependencies

# Build Spring PetClinic
git clone https://github.com/spring-projects/spring-petclinic.git
cd spring-petclinic
mvn clean package
java -jar target/spring-petclinic-*.jar
# Access: http://localhost:8080

21. Gradle Commands

# Install via SDKMAN
curl -s "https://sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
sdk install gradle 8.14
gradle --version

# Core tasks
./gradlew build                 # Compile + test + package
./gradlew clean                 # Delete build/
./gradlew test                  # Run unit tests
./gradlew assemble              # Package (no tests)
./gradlew check                 # All verifications
./gradlew run                   # Run app (needs 'application' plugin)
./gradlew clean build           # Clean + full rebuild

# Info
./gradlew tasks                 # List available tasks
./gradlew dependencies          # Dependency tree
./gradlew properties            # Project properties
./gradlew help --task build     # Help for specific task

# Build options
./gradlew build -x test         # Skip tests
./gradlew build --info          # Verbose logging
./gradlew build --debug         # Full debug output
./gradlew build --offline       # No network
./gradlew build --parallel      # Parallel execution
./gradlew build --scan          # Build scan (online)
./gradlew build --refresh-dependencies  # Re-download deps

# Multi-project
./gradlew :moduleName:taskName      # Specific module task
./gradlew :app:assembleDebug        # Android example

# Wrapper
gradle wrapper --gradle-version 8.7  # Update wrapper version
./gradlew wrapper                    # Regenerate wrapper files

# Build Spring PetClinic
git clone https://github.com/spring-projects/spring-petclinic.git
cd spring-petclinic
./gradlew build
java -jar build/libs/spring-petclinic-*.jar

22. Linux Patching

# Ubuntu / Debian — APT
sudo apt update
apt list --upgradable
sudo apt upgrade -y
sudo apt full-upgrade -y
sudo apt install --only-upgrade curl    # Single package
sudo apt autoremove -y
sudo apt autoclean

# One-liner full patch
sudo apt update && sudo apt full-upgrade -y && sudo apt autoremove -y && sudo apt autoclean

# Security patches only
sudo apt install unattended-upgrades -y
sudo unattended-upgrade --dry-run -v    # Preview only
sudo unattended-upgrade -v              # Apply

# Enable automatic security updates
sudo dpkg-reconfigure --priority=low unattended-upgrades

# Reboot check
cat /var/run/reboot-required
cat /var/run/reboot-required.pkgs
sudo reboot

# RHEL / CentOS
sudo yum update -y
sudo yum update --security -y          # Security only
sudo dnf update -y                     # CentOS 8+
sudo dnf update --security -y

# Check last update time
rpm -qa --last | head -20              # RPM history
cat /var/log/dpkg.log | grep "upgrade" # Debian history

# Scheduled patching with cron
crontab -e
# 0 2 * * 0 sudo apt update && sudo apt full-upgrade -y >> /var/log/patch.log 2>&1

23. WSL (Windows Subsystem for Linux)

# Install (PowerShell as Admin)
wsl --install                           # WSL2 + Ubuntu (default)
wsl --install -d Ubuntu-22.04          # Specific distro

# Management
wsl --list --online                     # Available distros
wsl --list --verbose                    # Running + version
wsl --set-default-version 2            # Set WSL2 as default
wsl --set-version Ubuntu 2             # Upgrade distro to WSL2
wsl --shutdown                         # Stop all WSL instances
wsl --terminate Ubuntu                 # Stop specific distro
wsl --unregister Ubuntu                # Remove distro (deletes data)
wsl --export Ubuntu ubuntu.tar         # Backup distro
wsl --import Ubuntu /path ubuntu.tar   # Restore distro

# Launch
wsl                                    # Launch default
wsl -d Ubuntu-22.04                    # Launch specific
ubuntu                                 # Launch Ubuntu directly
# Inside WSL — access Windows files
ls /mnt/c/Users/YourName/
ls /mnt/d/Projects/
cd /mnt/c/

# Patch Ubuntu in WSL
sudo apt update && sudo apt full-upgrade -y && sudo apt autoremove -y
# C:\Users\Name\.wslconfig — Resource limits
[wsl2]
memory=4GB
processors=2
swap=2GB
localhostForwarding=true

24. Environment Variables

env                         # List all environment variables
printenv                    # List all (same as env)
printenv PATH               # Specific variable
echo $HOME                  # Print variable
echo $USER
echo $SHELL
echo $PATH
echo $PWD

export MY_VAR="value"       # Set + export to child processes
export PATH=$PATH:/usr/local/bin    # Add to PATH
unset MY_VAR                # Remove variable

# Persistent variables — add to ~/.bashrc or ~/.bash_profile
echo 'export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64' >> ~/.bashrc
echo 'export PATH=$PATH:$JAVA_HOME/bin' >> ~/.bashrc
source ~/.bashrc            # Reload shell config

# System-wide: /etc/environment
# /etc/profile.d/*.sh for session-wide scripts

# Common variables
echo $JAVA_HOME
echo $MAVEN_HOME
echo $GRADLE_HOME
echo $DOCKER_HOST
echo $KUBECONFIG
echo $AWS_DEFAULT_REGION

25. Redirection & Pipes

# Redirection
command > file.txt          # Stdout to file (overwrite)
command >> file.txt         # Stdout to file (append)
command 2> error.log        # Stderr to file
command 2>> error.log       # Stderr append
command &> all.log          # Stdout + stderr to file
command > /dev/null         # Discard stdout
command 2>/dev/null         # Discard stderr
command > out.log 2>&1      # Both to same file (old syntax)
command < input.txt         # Read stdin from file
command << EOF              # Here document
  multi line input
EOF

# Pipes
command1 | command2                     # Pipe stdout to next
ps aux | grep nginx                     # Filter processes
cat file.txt | grep "error" | wc -l     # Count errors
ls -la | sort -k5 -n                    # Sort by size
cat /etc/passwd | cut -d: -f1 | sort   # Extract + sort
command | tee file.txt                  # Output to screen AND file
command | tee -a file.txt               # Output + append

# xargs — build commands from stdin
find . -name "*.log" | xargs rm
cat urls.txt | xargs -I{} curl -O {}
find . -name "*.sh" | xargs chmod +x
echo "file1 file2" | xargs -n1 ls      # One arg per line

# Command substitution
today=$(date +%Y-%m-%d)
files=$(ls /tmp/*.log)
count=$(wc -l < file.txt)
echo "Today is $today, files: $files"

Quick Reference — Most Used Commands

Category Commands
Navigate ls -la, cd, pwd, mkdir -p, rm -rf
Files cat, less, head -n, tail -f, cp -r, mv
Search grep -rni, find -name, locate, awk, sed
Permissions chmod 755, chown user:group, umask
Users useradd -m, usermod -aG, passwd, sudo
Processes ps aux, top, kill -9, nohup &
System uname -a, free -h, df -h, uptime
Network ip a, ss -tulnp, ping, curl, ssh
Transfer scp, sftp, rsync, wget
Archive tar -czvf, tar -xzvf, zip -r, unzip
Packages apt update && apt upgrade, yum update
Services systemctl start/stop/enable/status
Build mvn clean package, ./gradlew build
Cron crontab -e, crontab -l

Leave a comment

Turn on JavaScript to leave a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Please turn AdBlock off
Social Media Icons Powered by Acurax Web Design Company
Exit mobile version
%%footer%%