# does the swap file already exist? grep -q "swapfile" /etc/fstab
# if not then create it if [ $? -ne 0 ]; then echo'swapfile not found. Adding swapfile.' fallocate -l ${swapsize}M /swapfile chmod 600 /swapfile mkswap /swapfile swapon /swapfile echo'/swapfile none swap defaults 0 0' >> /etc/fstab else echo'swapfile found. No changes made.' fi
echo'--------------------------------------------' echo'Check whether the swap space created or not?' echo'--------------------------------------------' swapon --show
给文件添加执行权限。
1 2
$ sudo +x create_swap.sh
运行文件来创建和挂载交换文件。
1 2 3 4 5 6 7 8 9 10 11 12
$ sudo ./create_swap.sh
swapfile not found. Adding swapfile. Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes) no label, UUID=d9004261-396a-4321-a45f-9923e3e1328c -------------------------------------------- Check whether the swap space created or not? -------------------------------------------- NAME TYPE SIZE USED PRIO /dev/sda5 partition 2G 954.1M -1 /swapfile file 1024M 0B -2
# does the swap file exist? grep -q "swapfile" /etc/fstab
# if it does then remove it if [ $? -eq 0 ]; then echo'swapfile found. Removing swapfile.' sed -i '/swapfile/d' /etc/fstab echo"3" > /proc/sys/vm/drop_caches swapoff -a rm -f /swapfile else echo'No swapfile found. No changes made.' fi
echo'--------------------------------------------' echo'Check whether the swap space removed or not?' echo'--------------------------------------------' swapon --show
并给文件添加可执行权限。
1 2
$ sudo +x remove_swap.sh
运行脚本来移除并卸载交换文件。
1 2 3 4 5 6 7 8 9 10
$ sudo ./remove_swap.sh
swapfile found. Removing swapfile. swapoff: /dev/sda5: swapoff failed: Cannot allocate memory -------------------------------------------- Check whether the swap space removed or not? -------------------------------------------- NAME TYPE SIZE USED PRIO /dev/sda5 partition 2G 951.8M -1