
几天前我们写了一篇关于在 Linux 中 3 种创建交换文件的方法,它们是常见的方法,但是需要人工操作。
今天我发现了一个 Gary Stafford 写的 shell 小脚本(两个 shell 脚本,一个用于创建交换文件,另外一个用于移除交换文件),它可以帮助我们在 Linux 中创建/移除并且自动挂载交换文件。
默认这个脚本创建并挂载 512MB 的交换文件。如果你想要更多的交换空间和不同的文件名,你需要相应地修改脚本。修改脚本不是一件困难的事,因为这是一个容易上手而且很小的脚本。
推荐阅读: Linux 中 3 种简易创建或扩展交换空间的方法
如何检查当前交换文件大小
使用 free 和 swapon 命令检查已经存在交换空间。
$ free -htotal used free shared buff/cache availableMem:2.0G1.3G139M45M483M426MSwap:2.0G655M1.4G$ swapon--showNAME TYPE SIZE USED PRIO/dev/sda5 partition 2G655.2M-1
上面的输出显示我当前的交换空间是 2GB。
创建交换文件
创建 create_swap.sh 文件并添加下面的内容来自动化交换空间的创建和挂载。
$ nano create_swap.sh#!/bin/sh#size of swapfile in megabytesswapsize=1024# does the swap file already exist?grep-q "swapfile"/etc/fstab#ifnotthen create itif[ $?-ne 0];thenecho'swapfile not found. Adding swapfile.'fallocate -l ${swapsize}M /swapfilechmod600/swapfilemkswap/swapfileswapon/swapfileecho'/swapfile none swap defaults 0 0'>>/etc/fstabelseecho'swapfile found. No changes made.'fiecho'--------------------------------------------'echo'Check whether the swap space created or not?'echo'--------------------------------------------'swapon--show
给文件添加执行权限。
$ sudo+x create_swap.sh
运行文件来创建和挂载交换文件。
$ sudo./create_swap.shswapfile not found.Adding swapfile.Setting up swapspace version 1,size=1024MiB(1073737728 bytes)no label, UUID=d9004261-396a-4321-a45f-9923e3e1328c--------------------------------------------Check whether the swap space created ornot?--------------------------------------------NAME TYPE SIZE USED PRIO/dev/sda5 partition 2G954.1M-1/swapfile file1024M0B-2
你可以看到新的 1024M 的 swapfile。重启系统以使用新的交换文件。
移除交换文件
如果不再需要交换文件,接着创建 remove_swap.sh 文件并添加下面的内容来移除交换文件以及它的 /etc/fstab 挂载点。
$ nano remove_swap.sh#!/bin/sh# does the swap file exist?grep-q "swapfile"/etc/fstab#if it does then remove itif[ $?-eq 0];thenecho'swapfile found. Removing swapfile.'sed-i '/swapfile/d'/etc/fstabecho"3">/proc/sys/vm/drop_cachesswapoff-arm-f /swapfileelseecho'No swapfile found. No changes made.'fiecho'--------------------------------------------'echo'Check whether the swap space removed or not?'echo'--------------------------------------------'swapon--show
并给文件添加可执行权限。
$ sudo+x remove_swap.sh
运行脚本来移除并卸载交换文件。
$ sudo./remove_swap.shswapfile found.Removing swapfile.swapoff:/dev/sda5:swapoff failed:Cannot allocate memory--------------------------------------------Check whether the swap space removed ornot?--------------------------------------------NAME TYPE SIZE USED PRIO/dev/sda5 partition 2G951.8M-1
via: http://www.2daygeek.com/shell-script-create-add-extend-swap-space-linux/
作者:2DAYGEEK 译者:geekpi 校对:wxy
本文由 LCTT 原创编译,Linux中国 荣誉推出
本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-07/145332.htm
服务器评测





