-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswapcreate
executable file
·56 lines (44 loc) · 1.38 KB
/
swapcreate
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
#!/bin/sh
# Create a swapfile.
if [ "$1" = "" ]; then
echo "Usage: swapcreate <num> <loc>?"
echo " where <num> is the number of GiB to allocate"
echo " and <loc> is the folder to put the swapfile in."
echo " If no argument is provided for <loc>, it defaults"
echo " to whatever mounts at /dev/sda1."
exit 1
fi
if [ "$2" = "" ]; then
TARGET=$(findmnt /dev/sda1 | grep '/dev' | awk '{print $1}')
if [ "$TARGET" = "" ]; then
echo "Could not find a drive mounted at /dev/sda1."
exit 1
fi
SWAPFILE="$TARGET/.swapfile.img"
else
SWAPFILE="$2/.swapfile.img"
fi
NUMGI="$1""Gi"
NUMBYTES="$(numfmt $NUMGI --from=auto)"
FREEKILO="$(df /dev/sda | grep '/dev' | awk '{print $4}')K"
FREEBYTES="$(numfmt $FREEKILO --from=auto)"
FREEGI="$(numfmt $FREEKILO --from=auto --to=iec-i)"
ESWAPFILE="$(sudo swapon --show | grep '/.swapfile.img' | awk '{print $1}')"
if test -f "$ESWAPFILE"; then
echo "Swapfile already exists. Please call swapdestroy before creating another."
exit 1
fi
ALLOC_BLKSIZE="4096"
ALLOC_BLOCKS="$(expr $NUMBYTES / $ALLOC_BLKSIZE)"
echo "Creating swapfile: $SWAPFILE"
if command -v fallocate >/dev/null; then
sudo fallocate -l "$NUMGI""B" "$SWAPFILE"
else
sudo dd "if=/dev/zero" "of=$SWAPFILE" "bs=$ALLOC_BLKSIZE" "count=$ALLOC_BLOCKS"
fi
sudo chmod 600 "$SWAPFILE"
sudo mkswap "$SWAPFILE"
sudo swapon "$SWAPFILE"
echo "Swapfile created."
echo
sudo swapon --show