Skip to content

Instantly share code, notes, and snippets.

@akshayjai1
Created June 14, 2024 10:12
Show Gist options
  • Select an option

  • Save akshayjai1/f1b693aeca3b96f3db350b973c696729 to your computer and use it in GitHub Desktop.

Select an option

Save akshayjai1/f1b693aeca3b96f3db350b973c696729 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Define swap file location and size
swapfile=/swapfile
size=20G
# Check if the swapfile already exists
if [ -f $swapfile ]; then
echo "Swap file $swapfile already exists. Removing it first."
swapoff $swapfile
rm $swapfile
fi
# Create a swap file of the desired size
echo "Creating a $size swap file at $swapfile."
fallocate -l $size $swapfile
# Secure swap file by setting proper permissions
chmod 600 $swapfile
# Make the file usable as swap
mkswap $swapfile
# Activate the swap file
swapon $swapfile
# Backup the fstab file before modifying
cp /etc/fstab /etc/fstab.backup
# Add swap entry to /etc/fstab to make it permanent
echo "$swapfile none swap sw 0 0" | tee -a /etc/fstab
echo "Swap file created and activated. New system swap configuration:"
swapon --show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment