-
Notifications
You must be signed in to change notification settings - Fork 40
/
swap.sh
90 lines (81 loc) · 2.17 KB
/
swap.sh
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env bash
#Blog:https://www.moerats.com/
Green="\033[32m"
Font="\033[0m"
Red="\033[31m"
#root权限
root_need(){
if [[ $EUID -ne 0 ]]; then
echo -e "${Red}Error:This script must be run as root!${Font}"
exit 1
fi
}
#检测ovz
ovz_no(){
if [[ -d "/proc/vz" ]]; then
echo -e "${Red}Your VPS is based on OpenVZ,not supported!${Font}"
exit 1
fi
}
add_swap(){
echo -e "${Green}请输入需要添加的swap,建议为内存的2倍!${Font}"
read -p "请输入swap数值:" swapsize
#检查是否存在swapfile
grep -q "swapfile" /etc/fstab
#如果不存在将为其创建swap
if [ $? -ne 0 ]; then
echo -e "${Green}swapfile未发现,正在为其创建swapfile${Font}"
fallocate -l ${swapsize}M /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap defaults 0 0' >> /etc/fstab
echo -e "${Green}swap创建成功,并查看信息:${Font}"
cat /proc/swaps
cat /proc/meminfo | grep Swap
else
echo -e "${Red}swapfile已存在,swap设置失败,请先运行脚本删除swap后重新设置!${Font}"
fi
}
del_swap(){
#检查是否存在swapfile
grep -q "swapfile" /etc/fstab
#如果存在就将其移除
if [ $? -eq 0 ]; then
echo -e "${Green}swapfile已发现,正在将其移除...${Font}"
sed -i '/swapfile/d' /etc/fstab
echo "3" > /proc/sys/vm/drop_caches
swapoff -a
rm -f /swapfile
echo -e "${Green}swap已删除!${Font}"
else
echo -e "${Red}swapfile未发现,swap删除失败!${Font}"
fi
}
#开始菜单
main(){
root_need
ovz_no
clear
echo -e "———————————————————————————————————————"
echo -e "${Green}Linux VPS一键添加/删除swap脚本${Font}"
echo -e "${Green}1、添加swap${Font}"
echo -e "${Green}2、删除swap${Font}"
echo -e "———————————————————————————————————————"
read -p "请输入数字 [1-2]:" num
case "$num" in
1)
add_swap
;;
2)
del_swap
;;
*)
clear
echo -e "${Green}请输入正确数字 [1-2]${Font}"
sleep 2s
main
;;
esac
}
main