linuxswap
记录第n次创建启用并清理临时swap
摘要
时常要用 chatgpt 辅助生成 swap,记录下来方便
脚本
shell
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
#!/bin/bash
function create_swap {
SWAPFILE=$1
SIZE=$2
mkdir -p $(dirname "$SWAPFILE")
sudo dd if=/dev/zero of="$SWAPFILE" bs=1G count="$SIZE" status=progress
sudo chmod 600 "$SWAPFILE"
sudo mkswap "$SWAPFILE"
sudo swapon "$SWAPFILE"
echo "Swap file created and enabled at $SWAPFILE with size ${SIZE}G"
}
function clean_swap {
SWAPFILE=$1
if [ -f "$SWAPFILE" ]; then
sudo swapoff "$SWAPFILE"
sudo rm -f "$SWAPFILE"
echo "Swap file at $SWAPFILE has been removed."
else
echo "Swap file at $SWAPFILE does not exist."
fi
}
CLEAN_MODE=0
while getopts "c" opt; do
case $opt in
c)
CLEAN_MODE=1
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
shift $((OPTIND -1))
if [ "$CLEAN_MODE" -eq 1 ]; then
if [ "$#" -ne 1 ]; then
echo "Usage: $0 -c [swap file path]"
exit 1
fi
clean_swap $1
else
if [ "$#" -ne 2 ]; then
echo "Usage: $0 [swap file path] [size in GB]"
exit 1
fi
create_swap $1 $2
fi
运行
shell
123456
chmod +x create_swap.sh
# 创建 swap 文件
./create_swap.sh [swap file path] [size in GB]
# 清理 swap 文件
./create_swap.sh -c [swap file path]