Shell Scripting and C / Shell interactions


OK, so I'm trying to set up a shell script that tests if TCP is working and then restarts if it is not... Since I need to remotely admin my OS X box and sometimes TCP/sshd dies, having this script running daily as a crontab item would be great. Because then the system would reboot if there is ever a problem. And there is more general applicability to these questions, as well...

Anyhow, I'm not totally clear on how I might do a few things:
1) How to do conditional stuff? (ie: if no TCP then restart)
2) How to get output from shell commands into variables? (Then parse it with awk, I assume...)

Or should I learn Perl to do this?

I know python and C pretty well, but I don't know how I can run and get output from shell commands from within C or python programs... Does anyone else know this?

If anyone can answer my questions, that would be great. If anyone has a good link to a primer on shell scripting in general, I would be overjoyed.

Both questions depend on whether you\'re using sh or csh. (tcsh has the syntax of csh) I\'ve been writing for sh most recently, so I can be sure of my answers there.

<i>1) How to do conditional stuff? (ie: if no TCP then restart)</i>

<tt>if [ x${tcp_running} == x ]

Blasted vbcode is eating my indentation. Not to mention escaping my single quotes...

This assumes that you have some variable tcp_running, which has no value if it isn\'t running, and some string value if it is. The \"[\" is actually a link to the program called test, which exits with status 0 if the rest of its arguments are a true statement, non-zero otherwise. Test does string comparison here, so you need to concatenate the variable onto something in case the variable is empty, so sh won\'t complain

You can actually run any command you want after the \"if\", and it will do the \"then\" part if the command exits with 0, the optional \"else\" part otherwise.

<i>2) How to get output from shell commands into variables? </i>

Backquotes let you substitute the output of one command into another before running it.

<tt>sshd_running=`ps -ax | grep sshd`</tt>

Will put the appropriate line of ps\'s output into the variable, or leave it blank if sshd is down.

Incidentally, you might just be able to rerun the startup item that started sshd, without rebooting the whole machine. Probably the case with tcp too, but there I\'m really in over my head.