记录第n次创建启用并清理临时swap

摘要

时常要用 chatgpt 辅助生成 swap,记录下来方便

脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/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

运行

1
2
3
4
5
6
chmod +x create_swap.sh

# 创建 swap 文件
./create_swap.sh [swap file path] [size in GB]
# 清理 swap 文件
./create_swap.sh -c [swap file path]
- ETX   Thank you for reading -
  • Copyright: All posts on this blog except otherwise stated, All adopt CC BY-NC-ND 4.0 license agreement. Please indicate the source of reprint!