How Do You Write a Bash Script to Create Virtual Memory in the Size of 2 GB on a Linux Server?

Problem scenario
You want to dedicate 2 GB of your hard drive to be virtual memory (swap space for memory-intensive applications).  What should you do to script this that will work on any distribution of Linux (e.g., a RedHat derivative including CentOS/RHEL/Fedora, Debian/Ubuntu, or SUSE)?

Solution

Overview
We consider virtual memory to be a hybrid of RAM "and disk space that running processes can use. Swap space is the portion of virtual memory that is on the hard disk, used when RAM is full." The quoted section was taken from StackOverflow.

Warning:  You do not want to run this script more than once.  If there is a problem, you should try to correct it manually with this posting.  This posting modifies the /etc/fstab.  Use at your own risk!  If you want manual directions instead of a script, try this posting.

n.b. This script can work as a Startup script in GCP. When creating an instance in Google Cloud Platform, there is a field for Startup script. You may have to click the link "Management, disks, networking, SSH keys" to see the Startup script text field. The script below has been tested to work with Azure VMs.

Procedures
1.  Create a file called addswap.sh with this command:  vi /tmp/addswap.sh

2.  Place the content below in the addswap.sh file.  Then save it.

distro=$(cat /etc/*-release | grep NAME)

debflag=$(echo $distro | grep -i "ubuntu")
if [ -z "$debflag" ]
then   # If it is not Ubuntu, test if it is Debian.
  debflag=$(echo $distro | grep -i "debian")
  echo "determining Linux distribution..."
else
   echo "You have Ubuntu Linux!"
fi

if [ -z "$debflag" ]
then
   echo "Your Linux is NOT a Debian/Ubuntu derivative"
   echo "You may be using CentOS/RHEL/Fedora or SUSE"
   dd if=/dev/zero of=/mnt/2GB.swap count=2048 bs=1MiB
else
   echo "You are using either Ubuntu Linux or Debian Linux."
   fallocate -l 2G /mnt/2GB.swap
fi

mkswap /mnt/2GB.swap
swapon /mnt/2GB.swap

cp /etc/fstab ~/fstab.bak
cp /etc/sysctl.conf ~/sysctl.conf.bak

echo "/mnt/2GB.swap  none  swap  sw 0  0" >> /etc/fstab
echo "vm.swappiness=10" >> /etc/sysctl.conf

swapon -s
chmod 600 /mnt/2GB.swap

3.  Run the script with this command:  sudo bash /tmp/addswap.sh

With Ubuntu or Debian it is so fast you will not believe it.  Be prepared to wait if you are running a CentOS/RHEL/Fedora or SUSE distribution of Linux.  To see the results of your work, run this:  sudo top | grep Swap

Leave a comment

Your email address will not be published. Required fields are marked *