On Thu, May 07, 2009 at 10:12:59PM -0700, Jason Todd Slack-Moehrle wrote:
I need to write a script that I will manually start (or a cron job in future) but I need it to do a number of things in order one after another. How do i do that so everything gets dont as the steps depend on each other.
My questions:
- How do I execute each statement and make sure subsequent statements
are not executed until the previous is done?
Use the '&&' (logical "and") operator to pipeline the commands:
cd /foo/bar && tar cvf /path/to/tarball
This will only execute the "tar" command if the previous "cd" succeeded.
- How do I error check so if a step fails the script stops?
Most commands set a return status upon completion or error; this value is returned to the shell in the "$?" variable.
You could write the above as something like:
cd /foo/bar if [ $? -ne 0 ] then echo "cd failed ($?) - bailing out" exit 1 fi tar cvf /path/to/tarball if [ $? -ne 0 ] then echo "tar failed ($?) - bailing out" exit 2 fi
This checks the return status of each command, checks to see if it's not 0 (0 is "success") and if it is not alerts the user and exits with it's own error status.
- Since I run an SMTP Server on this box can I e-mail myself from
bash the nightly results?
Yep. "echo error message" | mail -s "script failure" user@dom.ain
Will mail the specified user a message containing "error message" with a subject of "script failure".
- when I want to run the scp to send over the file to another machine
for safety, how can I have it know the password to the machine I am scp'ing to?
You do this with public key authentication. "man ssh-keygen" for information on how to create a keypair.
My mind is going crazy sort of with the things that I could do to protect myself in case of a system failure and making restoring easier.
We've all been there.
Can anyone provide insight for me?
Test everything. On regular schedules. If you have the hardware available simulate a disaster condition and restore your backups to identical hardware to prove (to yourself and to management) that your disaster recovery steps actually do work.
John