Search code examples
shellawkcroncut

CUT command doesn't work in crontab


I have written shell script to monitor space

  echo "___________" `date` "___________"
df | tr -s ' ' $'\t' | cut -f5 > file.txt
echo `sed 's/Use//g' file.txt` > file.txt
echo `sed 's/%//g' file.txt` > file.txt
expression=`cat  file.txt | sed -e 's/ / /g'`
echo $expression
a=($expression)
#echo ${a[0]}
#echo ${a[1]}
#echo ${a[2]}
#echo ${a[3]}
#echo ${a[4]}
#echo ${a[5]}
#echo ${a[6]}
total=`expr ${a[0]} + ${a[1]} + ${a[2]} + ${a[3]} + ${a[4]} + ${a[5]} + ${a[6]}`
echo $total
server=`who`

if [ $total -ge 90 ]
then
    echo "greater"
else
    echo "Space occupied " $total "%"   
fi

When I run this script in terminal, it works fine. tr and cut commands works fine. But when I schedule this script in crontab, tr and cut command doesn't parse output of df command. Here is output of script when it is terminal

1 1 96 0 0 4 1
103
greater

output of script when it is scheduled in cron

Filesystem$1K-blocks$d$Available$$Mounted$on udev$1945488$4$1945484$1$/dev tmpfs$391332$836$390496$1$/run /dev/sda1$476684304$433659732$18787364$96$/ none$4$0$4$0$/sys/fs/cgroup none$5120$0$5120$0$/run/lock none$1956652$84020$1872632$5$/run/shm none$102400$56$102344$1$/run/user

Help me !


Solution

  • Not sure I follow what you are trying to get, but whenever you use crontab you should use the full path to all commands to be used as the path to all may not be available / set. Your code could be particularly shorter to:

    echo "___________$(/usr/bin/date)___________"
    total=$(/usr/bin/df | /usr/bin/awk 'NR > 1 && NR < 9{s+=$5}END{print s}')
    
    if (( total >= 90 ))
    then
      echo "greater"
    else
      echo "Space occupied $total%"
    fi