This how-to is about simple bash scripting. Scripts come in handy when you when you need to do certain tasks in a unix environment. They come in handy when you need to to a task in seconds that would be otherwise so repetitive that it would take you all day. “While loops” save the day when you need to constantly keep an eye on “something”. The possibilities are endless when it comes to bash scripting. If you get good enough you can even automate some of your daily tasks to save time for more important stuff. Bash scripts truly are powerful and should be a Unix admins best friend.
Here are a few I use a lot. And some tips on how to remember it all.
Netstat Checker
This simple while loop will look for daemons listening on a given port and return a count:
while: do uname -a; sleep 5; netstat -an | grep LISTEN | grep
Process Checker
Similar to the Netstat Checker is the process checker. Instead of looking for a port number here you give a process name.
while: do uname -a; sleep 5; ps -ef | grep
Doing “Something”
One great usage of this script is removing files form a directory. You may ask why not just use ‘rm -f’ like a normal person? Well there are times when you can have millions of files generated in a given directory. I had this happen once with a log rotation script that went crazy. In this case there are too many files for ‘rm’ to handle and it errors out. I use this nifty command to clean it up.
#cd to directory with all the files first!
for i in `find -f ./ ` :; do rm $i; done
Remembering and Expanding on it
I had it explained to me once and it helped me understand things quite a bit.
NAMES="Bob Jane Bill Jenny Joe"
export NAMES
for i in $NAMES: do echo $i; done
Basically your looking for something (a variable) in something (a list or file or values returned form a command) and then doing something (mv, rm, echo, cat, etc…) to it. It may sound crazy but its how I always remember the basics when i need to build a one liner to do something a little more complex.
Happy Scripting!
Leave a Reply