parse output of free -m|--mebi
and exits with an exit code
indicating whether it is safe to put whatever memory is
currently in swap memory back into physical memory.
this script is not designed to ( and will not ) run on its
own as with any awk
script.
free --mebi | awk -f /path/to/swap-status.awk
free --mebi | awk -f /path/to/swap-status.awk && [sudo] swapoff --all && [sudo] swapon --all
set some basic logging to debug the script by setting the
DEBUG variable for awk
.
free --mebi | awk -v DEBUG=true -f /path/to/swap-status.awk
set a shell alias that you can call to check if it is safe to empty the swap back into physical memory
alias swap?="free --mebi | awk -v DEBUG=$DEBUG -f $HOME/dev/awk/swap-status/swap-status.awk"
swap? # non-debug usage
swap? DEBUG=true # set DEBUG=true for one single usage
DEBUG=true
swap?
DEBUG=''
single-line to do the above ( I cannot think of why you
would want to use this rather than the one in shell alias usage,
but here it is anyway ) DEBUG=true && swap? && DEBUG=''
if you forget to unset the DEBUG
variable, it might get
picked up by other utilities that use it. The variable might
not do much with this tiny script, but it could do much more
with other bigger utilities. You might get thrown it into a
whole spam of debug logs and you might not even remember
that you had this flag on.
because this is an awk
script, one can naturally assume
that it plays nice with pipes. well, it does... mostly.
However, not much time has been spent making it pipe-safe.
for example, one obvious way to break the script is to pipe
the output of any other utility other than free
. or even
the output of the human-readable form of free
( free -h )
because it appends the memory unit to the output and you
cannot perform binary operations on strings. you should not
pipe the human-readable output of any utility to another
utility because they are obviously not human.
similarly, the script might not give a desired result if
anything other than the outputs of --mebi
/ --mega
because the check for 256MiB might fail or worse make a
favorable exit when it is not actually safe ( --gebi
/
--giga
).
the script, by default, has no kind of parseable output. the
script was not designed for the output to be parsed, but the
exit code to be used by a logical operator like &&
or ||
.
so no, you should not pipe the output of this script to any
other utility.
the script exits normally ( exit code 0
) if there will be
at least 256MiB free after putting all of the memory from
swap back into the physical memory or if swap is already empty.
if there will not be enough memory to put all of the swap memory back into physical memory, the script will mostly exit with exit code 255.
there is a fancy exit code logic if the difference is under 256MiB, then the script will exit an exit code with the difference of memory available. It was just dumb color that I decided to add to a boring script.