A collection of useful bash scripts for everyday Linux tasks.
- Clone this repository:
git clone https://github.com/yourusername/linux-scripts.git
cd linux-scripts- Make scripts executable:
chmod +x scripts/*.sh- (Optional) Add to your PATH:
echo 'export PATH="$PATH:~/linux-scripts/scripts"' >> ~/.bashrc
source ~/.bashrcDisplays comprehensive system information including CPU, memory, disk usage, and uptime.
#!/bin/bash
# System Information Script
# Displays key system metrics in a readable format
echo "================================"
echo " SYSTEM INFORMATION"
echo "================================"
echo ""
# Display hostname
echo "Hostname: $(hostname)"
# Display OS information
echo "OS: $(cat /etc/os-release | grep PRETTY_NAME | cut -d '"' -f 2)"
# Display kernel version
echo "Kernel: $(uname -r)"
# Display uptime
echo "Uptime: $(uptime -p)"
echo ""
echo "--- CPU Information ---"
# Display CPU model
echo "CPU: $(lscpu | grep 'Model name' | cut -d ':' -f 2 | xargs)"
# Display number of cores
echo "Cores: $(nproc)"
echo ""
echo "--- Memory Information ---"
# Display total and used memory
free -h | awk 'NR==2{printf "Total: %s | Used: %s | Free: %s\n", $2, $3, $4}'
echo ""
echo "--- Disk Usage ---"
# Display disk usage for all mounted filesystems
df -h | grep '^/dev/' | awk '{printf "%s: %s / %s (%s used)\n", $1, $3, $2, $5}'
echo ""
echo "================================"Creates timestamped backups of files or directories.
#!/bin/bash
# Backup Script
# Creates a compressed backup with timestamp
# Check if source is provided
if [ $# -eq 0 ]; then
echo "Usage: $0 <source_path> [destination_path]"
echo "Example: $0 ~/Documents ~/Backups"
exit 1
fi
# Set source and destination
SOURCE="$1"
DESTINATION="${2:-$HOME/Backups}"
# Check if source exists
if [ ! -e "$SOURCE" ]; then
echo "Error: Source '$SOURCE' does not exist"
exit 1
fi
# Create destination directory if it doesn't exist
mkdir -p "$DESTINATION"
# Create timestamp
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
# Get the base name of the source
BASENAME=$(basename "$SOURCE")
# Create backup filename
BACKUP_NAME="${BASENAME}_${TIMESTAMP}.tar.gz"
# Create the backup
echo "Creating backup of $SOURCE..."
tar -czf "$DESTINATION/$BACKUP_NAME" -C "$(dirname "$SOURCE")" "$(basename "$SOURCE")"
# Check if backup was successful
if [ $? -eq 0 ]; then
echo "Backup created successfully: $DESTINATION/$BACKUP_NAME"
# Display backup size
du -h "$DESTINATION/$BACKUP_NAME"
else
echo "Error: Backup failed"
exit 1
fiCleans temporary files and cache to free up disk space.
#!/bin/bash
# System Cleanup Script
# Removes temporary files and clears various caches
echo "Starting system cleanup..."
# Calculate initial disk usage
BEFORE=$(df -h / | awk 'NR==2{print $3}')
# Clear apt cache (for Debian/Ubuntu systems)
if command -v apt-get &> /dev/null; then
echo "Cleaning apt cache..."
sudo apt-get clean
sudo apt-get autoclean
fi
# Clear thumbnail cache
echo "Cleaning thumbnail cache..."
rm -rf ~/.cache/thumbnails/*
# Clear old logs (keeps last 3 days)
echo "Cleaning old system logs..."
sudo journalctl --vacuum-time=3d
# Remove old package versions (for Debian/Ubuntu)
if command -v apt-get &> /dev/null; then
echo "Removing old package versions..."
sudo apt-get autoremove -y
fi
# Clean trash
echo "Emptying trash..."
rm -rf ~/.local/share/Trash/*
# Clear browser cache (Firefox)
if [ -d ~/.mozilla/firefox ]; then
echo "Cleaning Firefox cache..."
rm -rf ~/.mozilla/firefox/*/cache2/*
fi
# Clear browser cache (Chrome/Chromium)
if [ -d ~/.cache/google-chrome ]; then
echo "Cleaning Chrome cache..."
rm -rf ~/.cache/google-chrome/*/Cache/*
fi
# Calculate final disk usage
AFTER=$(df -h / | awk 'NR==2{print $3}')
echo ""
echo "Cleanup complete!"
echo "Disk usage before: $BEFORE"
echo "Disk usage after: $AFTER"Finds the largest files in a directory.
#!/bin/bash
# Find Large Files Script
# Locates the largest files in a specified directory
# Set default values
DIRECTORY="${1:-.}"
NUMBER="${2:-10}"
echo "Finding the $NUMBER largest files in $DIRECTORY..."
echo ""
# Find and display largest files
find "$DIRECTORY" -type f -exec du -h {} + 2>/dev/null | \
sort -rh | \
head -n "$NUMBER" | \
awk '{printf "%s\t%s\n", $1, $2}'
echo ""
echo "Usage: $0 [directory] [number_of_files]"
echo "Example: $0 /home/user 20"Checks if specific ports are open on a host.
#!/bin/bash
# Port Checker Script
# Tests if ports are open on a specified host
# Check if host is provided
if [ $# -lt 2 ]; then
echo "Usage: $0 <host> <port1> [port2] [port3] ..."
echo "Example: $0 google.com 80 443 8080"
exit 1
fi
HOST="$1"
shift # Remove first argument (host) from the list
echo "Checking ports on $HOST..."
echo ""
# Loop through all provided ports
for PORT in "$@"; do
# Use timeout to prevent hanging
timeout 2 bash -c "echo >/dev/tcp/$HOST/$PORT" 2>/dev/null
if [ $? -eq 0 ]; then
echo "✓ Port $PORT is OPEN"
else
echo "✗ Port $PORT is CLOSED or filtered"
fi
doneTests internet connection speed.
#!/bin/bash
# Internet Speed Test Script
# Tests download and upload speeds using speedtest-cli
# Check if speedtest-cli is installed
if ! command -v speedtest-cli &> /dev/null; then
echo "speedtest-cli is not installed."
echo "Install it with: sudo apt install speedtest-cli"
exit 1
fi
echo "Testing internet speed..."
echo "This may take a moment..."
echo ""
# Run speedtest and format output
speedtest-cli --simple
echo ""
echo "Test completed at $(date)"Kills processes running on a specific port.
#!/bin/bash
# Kill Process on Port Script
# Terminates any process using the specified port
# Check if port number is provided
if [ $# -eq 0 ]; then
echo "Usage: $0 <port_number>"
echo "Example: $0 8080"
exit 1
fi
PORT="$1"
# Find process using the port
PID=$(lsof -t -i:$PORT)
# Check if a process was found
if [ -z "$PID" ]; then
echo "No process found running on port $PORT"
exit 0
fi
# Display process information
echo "Process using port $PORT:"
ps -p $PID -o pid,cmd
# Ask for confirmation
read -p "Do you want to kill this process? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
kill -9 $PID
echo "Process $PID killed successfully"
else
echo "Operation cancelled"
fiMonitors system processes and resource usage.
#!/bin/bash
# Process Monitor Script
# Displays top processes by CPU and memory usage
echo "=== TOP 10 PROCESSES BY CPU USAGE ==="
echo ""
ps aux --sort=-%cpu | head -n 11 | awk 'NR==1{print $0} NR>1{printf "%s\t%s%%\t%s\n", $11, $3, $2}'
echo ""
echo "=== TOP 10 PROCESSES BY MEMORY USAGE ==="
echo ""
ps aux --sort=-%mem | head -n 11 | awk 'NR==1{print $0} NR>1{printf "%s\t%s%%\t%s\n", $11, $4, $2}'
echo ""
echo "=== SYSTEM LOAD ==="
uptimeQuick git commit with timestamp message.
#!/bin/bash
# Quick Git Commit Script
# Adds all changes and commits with a timestamped message
# Check if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
echo "Error: Not in a git repository"
exit 1
fi
# Get custom message or use default
MESSAGE="${1:-Quick commit}"
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
FULL_MESSAGE="$MESSAGE - $TIMESTAMP"
# Show status
echo "Current status:"
git status --short
echo ""
read -p "Commit all changes? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
# Add all changes
git add .
# Commit with message
git commit -m "$FULL_MESSAGE"
echo ""
echo "Changes committed with message: $FULL_MESSAGE"
# Ask to push
read -p "Push to remote? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
git push
echo "Changes pushed successfully"
fi
else
echo "Commit cancelled"
fiStarts a simple HTTP server for development.
#!/bin/bash
# Development Server Script
# Starts a simple HTTP server in the current directory
PORT="${1:-8000}"
DIRECTORY="${2:-.}"
echo "Starting development server..."
echo "Directory: $DIRECTORY"
echo "Port: $PORT"
echo ""
echo "Access your site at: http://localhost:$PORT"
echo "Press Ctrl+C to stop the server"
echo ""
# Check if Python 3 is available
if command -v python3 &> /dev/null; then
cd "$DIRECTORY" && python3 -m http.server $PORT
# Fall back to Python 2
elif command -v python &> /dev/null; then
cd "$DIRECTORY" && python -m SimpleHTTPServer $PORT
else
echo "Error: Python is not installed"
exit 1
fiWatches files for changes and executes a command.
#!/bin/bash
# File Watcher Script
# Monitors files and runs a command when they change
# Check if sufficient arguments are provided
if [ $# -lt 2 ]; then
echo "Usage: $0 <file_or_directory> <command>"
echo "Example: $0 src/ 'npm run build'"
exit 1
fi
TARGET="$1"
COMMAND="$2"
# Check if inotify-tools is installed
if ! command -v inotifywait &> /dev/null; then
echo "inotify-tools is not installed."
echo "Install it with: sudo apt install inotify-tools"
exit 1
fi
echo "Watching $TARGET for changes..."
echo "Will execute: $COMMAND"
echo "Press Ctrl+C to stop"
echo ""
# Watch for changes and execute command
while inotifywait -r -e modify,create,delete "$TARGET" 2>/dev/null; do
echo ""
echo "Change detected! Running command..."
eval "$COMMAND"
echo ""
echo "Waiting for changes..."
doneFeel free to add your own scripts or improve existing ones! Please ensure:
- Scripts include helpful comments
- Error handling is implemented
- Usage examples are provided
MIT License - feel free to use and modify these scripts as needed.