I have been writing a lot of shell scripts lately as part of the C/Unix class that I'm taking at Harvard Extension. My familiarity with how the Unix shell and the underlying system works has grown exponentially. When I came across a problem earlier today, I subconsciously turned the problem into a shell script without even thinking about it!
The problem: "How can I check to make sure my program is running every 30 minutes and restart it if it's not?"
Answer:
# If myscript isn't running, restart it
ONLINE=`ps aux | grep -c myscript`
# 2 because grep myscript also finds 'grep myscript'
if [ $ONLINE -ne "2" ]; then
$MYSCRIPT_PATH/restart_service.sh
fi
I'm sure there are many better ways to solve this problem, but the fact that I instantly translated the problem into shell scripting code (and that it worked as expected on my first try) astonished me. I can see how good programmers who write in a particular language, and know the in's and out's the like the back of their hand can turn problems into code seamlessly (or know exactly where to look to find answers if they're unsure).
It's really amazing how easily you can solve simple problems when you have a deeper understanding of how the system works.
That's all. I just wanted to share my excitement. 🙂
That’s kinda how it starts and all. When it comes down, programming is programming is programming … and all. Learn to think as a programmer, then everything becomes a program in a way.
Though it’s a bit trite to mention a possible improvement at this point, might I suggest replacing the ps aux subshell with a call to pgrep? That particular utility (and its partner in crime, pkill) have helped me out a lot over the years.
I was hoping you would chime in with a suggestion. 🙂 Thanks!
A tip:
The command `pgrep` greps processes and shows by default only the PID for found processes, one per line. So you could change the value 2 to 1 and use this instead:
ONLINE=`pgrep myscript`
(The command pgrep is in the package procps together with uptime, free, top etc. in RedHat and CentOS at least).
Thanks so much for the tip, Terje! 🙂