Srikant
Srikant

Reputation: 1

The shell script does not execute the removing the files

I have the below script for removing the web cache and files from /tmp and /var/tmp directory to bring down the disk utilization percentage. When I execute the script it doesn't remove the files and gives nothing.

    #!/bin/bash

#set -x
#THRESHOLD=30
TEMP1=$(cd /tmp)
TEMP2=$(cd /var/tmp)
df -h | grep -v '^Filesystem' | awk '{print $1,$5}' | while read output;
do
  used=$(echo $output | awk '{print $5}' | cut -d '%' -f1)
  diskpart=$(echo $output | awk '{print $2}')
  if [[ "$used" -ge "30" ]]; then
    echo "Disk utilization percentage is more"
#    sync; echo 1 > /proc/sys/vm/drop_caches
    rm -rf "$TEMP1/*"
    rm -rf "$TEMP2/*"
  fi
done

Output below:

srikant@ubuntu:~$ ./example.sh 
srikant@ubuntu:~$ ./example.sh 
srikant@ubuntu:~$ 

The df -h command output:

srikant@ubuntu:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           393M   12M  382M   3% /run
/dev/sda1        19G  9.5G  8.2G  54% /
tmpfs           2.0G  272K  2.0G   1% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
tmpfs           393M     0  393M   0% /run/user/121
tmpfs           393M   52K  393M   1% /run/user/1000

I tried with sudo before rm -rf and while executing the script also. But still it is not working. Please help.

Upvotes: 0

Views: 423

Answers (1)

cdarke
cdarke

Reputation: 44354

When you generate output it only has two fields in it, the original $1 and $5 in the first awk '{print $1,$5}', for example /dev/sda1 and 54%. Then in:

used=$(echo $output | awk '{print $5}' | cut -d '%' -f1)

you only have these two fields, so the awk '{print $5}' part gives an empty string. It should be:

used=$(echo $output | awk '{print $2}' | cut -d '%' -f1)

In addition to that:

TEMP1=$(cd /tmp)
TEMP2=$(cd /var/tmp)

will be empty strings, because cd does not write anything to standard output. This should be:

TEMP1='/tmp'
TEMP2='/var/tmp'

The quotes are optional in this case.

Also:

 rm -rf "$TEMP1/*"

will look for a literal file called *, since filename expansion is not done inside quotes!

EDIT: My preferred solution would be to loose the external programs awk and cut:

temp1='/tmp'          # Avoid uppercase variable names
temp2='/var/tmp'      # they can collide with shell names

while read -r diskpart Size Used Avail Use Mounted
do
    # Remove the trailing %
    used=${Use%%%*}

    # A neater from of numeric comparison
    if (( used >= 30 ))  
    then
        echo "Disk utilization percentage is more"
        #sync; echo 1 > /proc/sys/vm/drop_caches

        # Note that putting * inside quotes won't be expanded
        rm -rf "$temp1"/*
        rm -rf "$temp2"/*
    fi
done < <(df -h)

Upvotes: 1

Related Questions