I am trying to disable the swap on our Linux machines with cron job
first I want to explain the right approach for disabling swap on linux machines ( we have RHEL 7.x )
the process should be like this
1 swapoff -a &
( in this example we used it as process )
2 comment the line with swap in /etc/fstab
as:
3 #/dev/mapper/vg_lab_swap swap swap defaults 0 0
we create cron job with name - swap_disable.cron
and cron jon looks like this ( we set the cron job for every min just for testing )
* * * * * root [[ ` swapon -s | wc | awk '{print $1}' ` -ne 0 ]] && [[ ` ps -ef | grep "swapoff -a" | grep -v grep | wc | awk '{print $1}' ` -eq 0 ]] && ( swapoff -a & ) && sed -ie '/\/dev\/mapper\/vg_lab_swap/ s/^#*/#/' /etc/fstab
so after waiting more then one min we saw that /etc/fstab
file not update and actually swap not disabled
so we set only the following line in the cron job to understand if something with our syntax is wrong
more swap_disable.cron
* * * * * root [[ ` swapon -s | wc | awk '{print $1}' ` -ne 0 ]] && [[ ` ps -ef | grep "swapoff -a" | grep -v grep | wc | awk '{print $1}' ` -eq 0 ]] && echo why_line_not_works >/tmp/file.txt
explain:
swapon -s | wc | awk '{print $1}'
- verify if swap is disabled
ps -ef | grep "swapoff -a" | grep -v grep | wc | awk '{print $1}'
- verify if swapoff process already running
and unfortunately this above simple line also not works , and file /tmp/file.tx
t not created
so what is wrong in my cron job?
why the line:
[[ ` swapon -s | wc | awk '{print $1}' ` -ne 0 ]] && [[ ` ps -ef | grep "swapoff -a" | grep -v grep | wc | awk '{print $1}' ` -eq 0 ]] && echo why_line_not_works >/tmp/file.txt
is working fine on linux shell console but not from cron job?
example when we run it from sh
cron.d]# sh
sh-4.2# [ ` swapon -s | wc | awk '{print $1}' ` -ne 0 ] && [ ` ps -ef | grep "swapoff -a" | grep -v grep | wc | awk '{print $1}' ` -eq 0 ] && echo why
why
Make sure you declare your SHELL and PATH in your crontab to not have to specify absolute paths for all the commands you are running.
Try the following under your cron.d file:
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
* * * * * root [[ ` swapon -s | wc | awk '{print $1}' ` -ne 0 ]] && [[ ` ps -ef | grep "swapoff -a" | grep -v grep | wc | awk '{print $1}' ` -eq 0 ]] && echo why_line_not_works >/tmp/file.txt