This page provides handy shell script examples for Linux automation, system maintenance, and troubleshooting.
# Print Hello World
echo "Hello, World"
# Create a directory
mkdir -p ~/scripts
# Check disk usage
df -h
# Show current IP address
ip a | grep inet
# Loop through files in a folder
for file in *.txt; do echo "$file"; done
# View contents of a file
cat filename.txt
# Change to a directory
cd ~/scripts
# Search for a word in a file
grep "search_term" filename.txt
# Change file permissions
chmod +x script.sh
# List files with details
ls -lah
# Move or rename a file
mv oldname.txt newname.txt
# Remove a file
rm unwanted.txt
# Copy a file
cp source.txt destination.txt
# Loop through lines in a file
while IFS= read -r line; do echo "$line"; done < filename.txt
# Show current date and time
date
# Check memory usage
free -h
# See who is logged in
who
# Run a command every 5 seconds
watch -n 5 'ls -l'
# Update system (Debian/Ubuntu)
sudo apt update && sudo apt upgrade -y
# Clean up unnecessary packages
sudo apt autoremove -y
# Show top 10 memory-hungry processes
ps aux --sort=-%mem | head -n 10
# Check open ports
sudo netstat -tulp
# Check system uptime
uptime
# Show system resource usage (CPU, memory, load)
top
# List all installed packages (Debian/Ubuntu)
dpkg --get-selections
# Check disk space usage for each directory in root
sudo du -sh /* 2>/dev/null
# Check system logs (last 100 lines)
sudo journalctl -xe | tail -n 100
# List hardware info
lshw -short
# Check swap usage
swapon --show
# Show active systemd services
systemctl list-units --type=service --state=running
# Reboot the system
sudo reboot
# Check for failed systemd services
systemctl --failed
# Show system boot time
who -b
# Search logs for a specific service (e.g., ssh)
journalctl -u ssh.service
# Find files larger than 100MB
find / -type f -size +100M
# Delete .log files older than 7 days
find /var/log -type f -name "*.log" -mtime +7 -delete
# Backup a directory with timestamp
tar -czvf backup_$(date +%F).tar.gz /etc/
# Simple backup script
#!/bin/bash
SRC="/home/user/Documents"
DST="/mnt/backup"
tar -czf $DST/backup_$(date +%F).tar.gz $SRC
# Add to cron for daily 2 AM backup
0 2 * * * /home/user/scripts/backup.sh
# List all users
cut -d: -f1 /etc/passwd
# Disable root SSH login
sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sudo systemctl restart sshd
# Save scripts with .sh extension and run with:
chmod +x script.sh
./script.sh
Use #!/bin/bash at the top for clarity
Test scripts in a safe environment before using on servers