Bash script loop to monitor something like disk space

By | September 26, 2015
ilovebash

ilovebash

Loops in bash are something Ive covered before, including parsing a file record by record (HERE), but one of the other uses I have frequently is a never ending script which watches something changing.

Maybe a good example of this is if you are doing a large file transfer (scp as example) and you want to watch that the disk doesnt fill up before it finishes. The bash script loop WHILE is your friend for a quick and dirty way to show current space used. Here is how you do it.

Bash script loop to watch or monitor something constantly

As you may know already the command to view disk space usage is this :

df -k

The task you want to achieve is to save you keeping typing that again and again.

Here is the code to do it and show you the current time as well :

while [ 1 ] ; do

date
df -k
sleep 10

done

And thats it !! The while [ 1 ] is the never ending bash script loop (break out with a ctrl c) and then the script displays the date / time, shows the disk space, and sleeps 10 seconds and then loops again.

Want to make the date/time stand out a bit more? Reverse the colour of the screen on it by adding this :

while [ 1 ] ; do

tput smso
date
tput rmso
df -k
sleep 10

done

The tput smso reverses the text colours, and the tput rmso removes the reverse colours. There are more options for the tput command but this is simple and does the job.

If you liked this quick tutorial for monitoring something then share it with your friends, and if you want any more tutorials on different subjects then reply to this post or email me on admin@bashworkz.com

Check out -  Bash remove duplicate lines without sorting

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.