Last active
December 29, 2023 20:47
-
-
Save jorishr/49c2062c97707daaf856d09fcf4b8d21 to your computer and use it in GitHub Desktop.
Add a temporary swap file to a Ubuntu server
This file contains 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 -e | |
echo -e "\e[1;34m╔══════════════════════════════════════════╗" | |
echo -e "║ \e[1;36mSwap File Setup Script\e[1;34m ║" | |
echo -e "╚══════════════════════════════════════════╝\e[0m\n" | |
echo -e "\e[1;34mStep 1: Setup the Swap File\e[0m" | |
echo -e "Creating swap file..." | |
SWAP_FILE="/swapfile" | |
MAX_MINUTES=120 | |
# Prompt user for input if no argument is provided | |
if [ "$#" -eq 0 ]; then | |
read -p "Enter the duration in minutes (max. $MAX_MINUTES minutes): " USER_INPUT_MINUTES | |
# Validate user input | |
if ! [[ "$USER_INPUT_MINUTES" =~ ^[0-9]+$ ]] || [ "$USER_INPUT_MINUTES" -gt "$MAX_MINUTES" ]; then | |
echo "Invalid input. Please enter a valid number less than or equal to $MAX_MINUTES." | |
exit 1 | |
fi | |
DURATION="$USER_INPUT_MINUTES" | |
else | |
# Validate command line argument | |
if ! [[ "$1" =~ ^[0-9]+$ ]] || [ "$1" -gt "$MAX_MINUTES" ]; then | |
echo "Invalid argument. Please enter a valid number less than or equal to $MAX_MINUTES." | |
exit 1 | |
fi | |
DURATION="$1" | |
fi | |
SWAP_SIZE="8G" | |
sudo fallocate -l $SWAP_SIZE $SWAP_FILE | |
sudo chmod 600 $SWAP_FILE | |
sudo mkswap $SWAP_FILE | |
echo -e "\n\e[1;34mStep 2: Activate the Swap File\e[0m" | |
echo -e "Activating swap file..." | |
sudo swapon $SWAP_FILE | |
echo -e "\e[1;34mStep 3: Wait for $DURATION minutes in the background\e[0m" | |
echo -e "Waiting for $DURATION minutes..." | |
{ | |
(sleep 15m && { | |
echo -e "\e[1;34mStep 4: Remove the Swap File\e[0m" | |
echo -e "\e[1;36m[$(date '+%Y-%m-%d %H:%M:%S')] Removing swap file...\e[0m" | |
sudo swapoff $SWAP_FILE | |
sudo rm $SWAP_FILE | |
echo -e "\e[1;32m[$(date '+%Y-%m-%d %H:%M:%S')] Swap file removed.\e[0m" | |
} & disown ) | |
} >> /home/jorishr/.setup-swapfile.log 2>&1 & | |
echo -e "Background process started. The terminal is now free." | |
echo -e "Swapfile should be removed in $DURATION minutes. Result in log file: .setup-swapfile.log in home folder.\n" | |
echo -e "\e[1;34m╔══════════════════════════════════════════╗" | |
echo -e "║ \e[1;36mSwap File Setup Script Completed\e[1;34m ║" | |
echo -e "╚══════════════════════════════════════════╝\e[0m" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment