Revisão | a50ec831988ad8e62bcfa6dbe861534b3bc5638f (tree) |
---|---|
Hora | 2015-04-20 04:47:09 |
Autor | Lorenzo Isella <lorenzo.isella@gmai...> |
Commiter | Lorenzo Isella |
A script to clear and reactivate the swap only when there is free memory available.
@@ -0,0 +1,32 @@ | ||
1 | +#!/bin/bash | |
2 | + | |
3 | +# Make sure that all text is parsed in the same language | |
4 | +# export LC_MESSAGES=en_US.UTF-8 | |
5 | +# export LC_COLLATE=en_US.UTF-8 | |
6 | +# export LANG=en_US.utf8 | |
7 | +# export LANGUAGE=en_US:en | |
8 | +# export LC_CTYPE=en_US.UTF-8 | |
9 | + | |
10 | +# Calculate how much memory and swap is free | |
11 | +free_data="$(free)" | |
12 | +mem_data="$(echo "$free_data" | grep 'Mem:')" | |
13 | +free_mem="$(echo "$mem_data" | awk '{print $4}')" | |
14 | +buffers="$(echo "$mem_data" | awk '{print $6}')" | |
15 | +cache="$(echo "$mem_data" | awk '{print $7}')" | |
16 | +total_free=$((free_mem + buffers + cache)) | |
17 | +used_swap="$(echo "$free_data" | grep 'Swap:' | awk '{print $3}')" | |
18 | + | |
19 | +echo -e "Free memory:\t$total_free kB ($((total_free / 1024)) MB)\nUsed swap:\t$used_swap kB ($((used_swap / 1024)) MB)" | |
20 | + | |
21 | +# Do the work | |
22 | +if [[ $used_swap -eq 0 ]]; then | |
23 | + echo "Congratulations! No swap is in use." | |
24 | +elif [[ $used_swap -lt $total_free ]]; then | |
25 | + echo "Freeing swap..." | |
26 | + swapoff -a | |
27 | + swapon -a | |
28 | +else | |
29 | + echo "Not enough free memory. Exiting." | |
30 | + exit 1 | |
31 | +fi | |
32 | + |