Labels

Saturday, 13 October 2012

My first shell script !!!

When I started my career as a QA engineer, I was told by lead that I need to run some commands on daily basis before starting with my regular work. He instructed me to run below steps,

#1 Run df -k command to find out the amount of disk space free


#2 If the 'Use %' more than 50%, then go to that file system by entering 'cd <file system>' . In our case it is cd /usr/bin

#3 Run the 'ls -lS' command to sort out the files by size in descending order. [Note: you can use ls -lrS to sort in a reverse order]




#4 delete the file using 'rm -f <filename>'. [Note. In some cases you don't want to delete the filename but only file content then you can issue > <filename>

# 5 Repeat the steps 1-4 for other files in the file system

#6 Repeat the steps 1-5 for other file systems as well

These commands were doing a nice job and I was so much exited to running these steps for couple of days and then started boring ..........

I started thinking, thinking ...and reading, reading .... And finally got an idea to automate this boring work.
Here you go:

$ cat diskcleanup.sh
# /usr/bin
# Author: Sundar Pari
# Purpose of the script: Cleaning up the disk space
# Caution: DO NOT run this script with removing comment in 'rm -r $fname' until unless you really want to cleanup your disk

if [ -e fdetails.txt ]
then
        rm -f fdetails.txt
fi
# Here, I am cleaning up the file system which are more than 85% used
# fdetails.txt has the file system names which are moren than 85% used
# fnames.txt contains files which are going to be deleted

df -k | awk '{ split ($5,arr,"%"); if (arr[1] > 85 && arr[1] != "Use") print $1 }' > fdetails.txt

if [ -e fdetails.txt ]
then
        while read line
        do
                echo "Changing directory: $line"
                cd $line
                ls -S > fnames.txt
                while read fname
                do
                        echo "Deleting the File : $fname"
                        # rm -f $fname
                done <fnames.txt
        done <fdetails.txt
fi

I won't say this is the best optimized script but it will do a decent job. Try it! Enjoy :-)
We can instrument this script into Cron Jobs, so that it will be triggered at specified intervals. We will see Cron Jobs later. 

Last but not least, you can do wonders with 'awk' command. Read more over here:
http://www.freeos.com/guides/lsst/ch07.html

awk sample outputs are:



'NF' - you can expect this number of interviews


Thanks for your time and patience !

No comments:

Post a Comment