Last active
August 24, 2025 19:10
-
-
Save rowland007/8a9cb32243ab5711aa59131ff1487370 to your computer and use it in GitHub Desktop.
This script will automate the process of creating a swap file, ensuring that it is run with the necessary permissions and handling user input effectively.
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 | |
# Ensure the script is run as root | |
if [ "$EUID" -ne 0 ]; then | |
echo "Please run as root (use sudo)." | |
exit 1 | |
fi | |
# Function to create or resize the swap file | |
create_swap() { | |
local size=$1 | |
# Disable current swap | |
swapoff -a | |
# Create or resize the swap file | |
fallocate -l "${size}" /swapfile | |
# Set correct permissions | |
chmod 600 /swapfile | |
# Set up the swap file | |
mkswap /swapfile | |
# Enable the swap file | |
swapon /swapfile | |
# Verify the swap | |
echo "Swap file created and enabled. Current swap status:" | |
free -h | |
} | |
# Check if the swap file already exists | |
if [ -f /swapfile ]; then | |
current_size=$(du -h /swapfile | cut -f1) | |
echo "The swap file already exists with a size of: $current_size" | |
read -p "Do you want to resize the swap file? (yes/no): " confirm | |
confirm=${confirm,,} # Convert to lowercase | |
if [[ "$confirm" != "yes" && "$confirm" != "y" ]]; then | |
echo "Operation canceled." | |
exit 0 | |
fi | |
# Prompt for the new size if the user wants to overwrite | |
while true; do | |
read -p "What size would you like the new swap file? (In Gigabytes): " size | |
size=${size^^} # Convert to uppercase | |
if [[ "$size" =~ ^[0-9]+G$ ]]; then | |
create_swap "$size" | |
break | |
else | |
echo "Invalid input. Please enter a number followed by 'G' (e.g., 5G)." | |
fi | |
done | |
else | |
# Prompt the user for the size of the swap file | |
while true; do | |
read -p "What size would you like the swap file? (In Gigabytes): " size | |
size=${size^^} # Convert to uppercase | |
if [[ "$size" =~ ^[0-9]+G$ ]]; then | |
create_swap "$size" | |
break | |
else | |
echo "Invalid input. Please enter a number followed by 'G' (e.g., 5G)." | |
fi | |
done | |
# Make the change permanent | |
echo "/swapfile none swap sw 0 0" >> /etc/fstab | |
exit 0 | |
fi | |
# If the swap file exists, resize it | |
create_swap "$size" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment