Created
October 5, 2025 00:01
-
-
Save zuedev/635ca8d88cebdc8c4795115af028ca32 to your computer and use it in GitHub Desktop.
Create and enable a swap file on Linux systems.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| set -euo pipefail | |
| # Color codes for output | |
| RED='\033[0;31m' | |
| GREEN='\033[0;32m' | |
| YELLOW='\033[1;33m' | |
| BLUE='\033[0;34m' | |
| NC='\033[0m' # No Color | |
| # Logging functions | |
| log_info() { | |
| echo -e "${BLUE}[INFO]${NC} $1" | |
| } | |
| log_success() { | |
| echo -e "${GREEN}[SUCCESS]${NC} $1" | |
| } | |
| log_warning() { | |
| echo -e "${YELLOW}[WARNING]${NC} $1" | |
| } | |
| log_error() { | |
| echo -e "${RED}[ERROR]${NC} $1" >&2 | |
| } | |
| # Show usage | |
| show_usage() { | |
| cat << EOF | |
| Usage: $0 [OPTIONS] {size} | |
| Create and enable a swap file on Linux systems. | |
| Arguments: | |
| size Size of swap file (e.g., 2G, 512M, 4096M) | |
| Options: | |
| -p, --path PATH Custom path for swap file (default: /swapfile) | |
| -s, --swappiness N Set swappiness value 0-100 (default: 60) | |
| -r, --remove Remove existing swap file | |
| -c, --check Check current swap status | |
| -h, --help Show this help message | |
| Examples: | |
| $0 4G # Create 4GB swap at /swapfile | |
| $0 2G -p /mnt/swap.img # Create 2GB swap at custom path | |
| $0 4G -s 10 # Create 4GB swap with swappiness 10 | |
| $0 --remove # Remove swap file | |
| $0 --check # Check current swap status | |
| EOF | |
| exit 0 | |
| } | |
| # Check current swap status | |
| check_swap_status() { | |
| log_info "Current swap configuration:" | |
| echo | |
| if command -v swapon &> /dev/null; then | |
| swapon --show | |
| echo | |
| free -h | grep -E "Mem:|Swap:" | |
| echo | |
| if [ -f /proc/sys/vm/swappiness ]; then | |
| log_info "Current swappiness: $(cat /proc/sys/vm/swappiness)" | |
| fi | |
| else | |
| log_error "swapon command not found" | |
| exit 1 | |
| fi | |
| exit 0 | |
| } | |
| # Remove swap file | |
| remove_swap() { | |
| log_info "Removing swap file at $SWAP_PATH" | |
| # Check if swap file exists | |
| if [ ! -f "$SWAP_PATH" ]; then | |
| log_error "Swap file $SWAP_PATH does not exist" | |
| exit 1 | |
| fi | |
| # Turn off swap | |
| if swapon --show | grep -q "$SWAP_PATH"; then | |
| log_info "Disabling swap file..." | |
| $SUDO swapoff "$SWAP_PATH" | |
| log_success "Swap disabled" | |
| fi | |
| # Remove from fstab | |
| if grep -q "$SWAP_PATH" /etc/fstab; then | |
| log_info "Removing from /etc/fstab..." | |
| $SUDO sed -i "\|$SWAP_PATH|d" /etc/fstab | |
| log_success "Removed from /etc/fstab" | |
| fi | |
| # Remove file | |
| log_info "Removing swap file..." | |
| $SUDO rm -f "$SWAP_PATH" | |
| log_success "Swap file removed successfully" | |
| exit 0 | |
| } | |
| # Validate size format | |
| validate_size() { | |
| local size=$1 | |
| if ! echo "$size" | grep -qE '^[0-9]+[MGT]$'; then | |
| log_error "Invalid size format: $size" | |
| log_error "Size must be a number followed by M, G, or T (e.g., 2G, 512M, 1T)" | |
| exit 1 | |
| fi | |
| } | |
| # Convert size to bytes for validation | |
| size_to_bytes() { | |
| local size=$1 | |
| local number=$(echo "$size" | sed 's/[^0-9]*//g') | |
| local unit=$(echo "$size" | sed 's/[0-9]*//g') | |
| case "$unit" in | |
| M) echo $((number * 1024 * 1024)) ;; | |
| G) echo $((number * 1024 * 1024 * 1024)) ;; | |
| T) echo $((number * 1024 * 1024 * 1024 * 1024)) ;; | |
| *) echo 0 ;; | |
| esac | |
| } | |
| # Check available disk space | |
| check_disk_space() { | |
| local swap_dir=$(dirname "$SWAP_PATH") | |
| local required_bytes=$(size_to_bytes "$SWAP_SIZE") | |
| local available_bytes=$(df -B1 "$swap_dir" | awk 'NR==2 {print $4}') | |
| if [ "$required_bytes" -gt "$available_bytes" ]; then | |
| log_error "Insufficient disk space" | |
| log_error "Required: $SWAP_SIZE, Available: $(numfmt --to=iec-i --suffix=B $available_bytes)" | |
| exit 1 | |
| fi | |
| log_success "Sufficient disk space available" | |
| } | |
| # Validate swappiness value | |
| validate_swappiness() { | |
| if [ "$SWAPPINESS" -lt 0 ] || [ "$SWAPPINESS" -gt 100 ]; then | |
| log_error "Swappiness must be between 0 and 100" | |
| exit 1 | |
| fi | |
| } | |
| # Parse command line arguments | |
| SWAP_SIZE="" | |
| SWAP_PATH="/swapfile" | |
| SWAPPINESS=60 | |
| REMOVE_SWAP=false | |
| CHECK_STATUS=false | |
| while [[ $# -gt 0 ]]; do | |
| case $1 in | |
| -h|--help) | |
| show_usage | |
| ;; | |
| -p|--path) | |
| SWAP_PATH="$2" | |
| shift 2 | |
| ;; | |
| -s|--swappiness) | |
| SWAPPINESS="$2" | |
| shift 2 | |
| ;; | |
| -r|--remove) | |
| REMOVE_SWAP=true | |
| shift | |
| ;; | |
| -c|--check) | |
| CHECK_STATUS=true | |
| shift | |
| ;; | |
| *) | |
| if [ -z "$SWAP_SIZE" ]; then | |
| SWAP_SIZE="$1" | |
| else | |
| log_error "Unknown option: $1" | |
| show_usage | |
| fi | |
| shift | |
| ;; | |
| esac | |
| done | |
| # Setup sudo if needed | |
| SUDO='' | |
| if [ "$(id -u)" -ne 0 ]; then | |
| log_warning "Root access required" | |
| if sudo true; then | |
| SUDO='sudo' | |
| log_success "Sudo access granted" | |
| else | |
| log_error "Unable to obtain root access" | |
| exit 1 | |
| fi | |
| fi | |
| # Handle check status | |
| if [ "$CHECK_STATUS" = true ]; then | |
| check_swap_status | |
| fi | |
| # Handle remove swap | |
| if [ "$REMOVE_SWAP" = true ]; then | |
| if [ -z "$SWAP_SIZE" ]; then | |
| SWAP_PATH="/swapfile" | |
| fi | |
| remove_swap | |
| fi | |
| # Validate required arguments | |
| if [ -z "$SWAP_SIZE" ]; then | |
| log_error "Size argument is required" | |
| show_usage | |
| fi | |
| # Validate inputs | |
| validate_size "$SWAP_SIZE" | |
| validate_swappiness | |
| # Display configuration | |
| echo | |
| log_info "Swap Setup Configuration:" | |
| log_info "=========================" | |
| log_info "Size: $SWAP_SIZE" | |
| log_info "Path: $SWAP_PATH" | |
| log_info "Swappiness: $SWAPPINESS" | |
| echo | |
| # Check if swap file already exists | |
| if [ -f "$SWAP_PATH" ]; then | |
| log_warning "Swap file already exists at $SWAP_PATH" | |
| read -p "Do you want to remove it and create a new one? (y/N): " -n 1 -r | |
| echo | |
| if [[ $REPLY =~ ^[Yy]$ ]]; then | |
| if swapon --show | grep -q "$SWAP_PATH"; then | |
| log_info "Disabling existing swap..." | |
| $SUDO swapoff "$SWAP_PATH" | |
| fi | |
| $SUDO rm -f "$SWAP_PATH" | |
| log_success "Removed existing swap file" | |
| else | |
| log_info "Aborted" | |
| exit 0 | |
| fi | |
| fi | |
| # Check available disk space | |
| check_disk_space | |
| # Create swap file | |
| log_info "Creating swap file..." | |
| if $SUDO fallocate -l "$SWAP_SIZE" "$SWAP_PATH"; then | |
| log_success "Swap file allocated" | |
| else | |
| log_warning "fallocate failed, falling back to dd..." | |
| $SUDO dd if=/dev/zero of="$SWAP_PATH" bs=1M count=$(echo "$SWAP_SIZE" | sed 's/[^0-9]*//g') status=progress | |
| log_success "Swap file created with dd" | |
| fi | |
| # Set proper permissions | |
| log_info "Setting permissions..." | |
| $SUDO chmod 600 "$SWAP_PATH" | |
| log_success "Permissions set to 600" | |
| # Setup swap | |
| log_info "Setting up swap space..." | |
| $SUDO mkswap "$SWAP_PATH" | |
| log_success "Swap space created" | |
| # Enable swap | |
| log_info "Enabling swap..." | |
| $SUDO swapon "$SWAP_PATH" | |
| log_success "Swap enabled" | |
| # Add to fstab if not already present | |
| if ! grep -q "$SWAP_PATH" /etc/fstab; then | |
| log_info "Adding to /etc/fstab..." | |
| echo "$SWAP_PATH none swap sw 0 0" | $SUDO tee -a /etc/fstab > /dev/null | |
| log_success "Added to /etc/fstab" | |
| else | |
| log_warning "Entry already exists in /etc/fstab" | |
| fi | |
| # Set swappiness | |
| log_info "Setting swappiness to $SWAPPINESS..." | |
| $SUDO sysctl vm.swappiness="$SWAPPINESS" > /dev/null | |
| echo "vm.swappiness=$SWAPPINESS" | $SUDO tee -a /etc/sysctl.conf > /dev/null | |
| log_success "Swappiness configured" | |
| # Display final status | |
| echo | |
| log_success "Swap setup completed successfully!" | |
| echo | |
| log_info "Final swap status:" | |
| swapon --show | |
| echo | |
| free -h | grep -E "Mem:|Swap:" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment