[CentOS] Bash Script help...

Fri May 8 05:39:39 UTC 2009
Ray Van Dolson <rayvd at bludgeon.org>

On Thu, May 07, 2009 at 10:12:59PM -0700, Jason Todd Slack-Moehrle wrote:
> Hi All,
> 
> 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.
> 
> Example:
> 
> cd /system_backups/
> 
> tar cvf apache-conf.tar /etc/httpd/conf/*
> gzip -v9 apache-conf.tar
> 
> tar cvf apache-data.tar /var/www/*
> gzip -v9 apache-data.tar
> 
> then last step...
> tar cvf <current_date>-system_backup.tar <all> the gzip files above
> gzip -v9 <current_date>-system_backup.tar
> 
> scp <current_date>-system_backup.tar.gz user at 10.0.0.1:/.
> etc...etc....
> 
> My questions:
> 1. How do I execute each statement and make sure subsequent statements  
> are not executed until the previous is done?

This will happen on its own unless you intentionally force a command
into the background with &.

> 
> 2. How do I error check so if a step fails the script stops?

You can use && or || or check the status of $?.  For example:

tar cvfz apache-conf.tar.gz /etc/httpd/conf/*

if [ $? != 0 ]; then
  echo "Error creating tar file."
  exit 255
fi

$? contains the exit code of the previously executed command.

Or something like...

tar cvfz apache-conf.tar.gz /etc/httpd/conf/* || \
  { echo "Problem creating tar file."; exit 255; }

The first method is probably a little more clear.

> 
> 3. Since I run an SMTP Server on this box can I e-mail myself from  
> bash the nightly results?

Sure.  If you call it from cron, anything on stdout will be emailed to
the user running the job.  Alternately you can call the "mail" command.
You can also surround several commands and pipe their output to a
command:

(
echo "Test"
echo "Test 2"
) | mail email at email.com

> 4. 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'll want to set up ssh keys for this.

> 
> 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.
> 
> Can anyone provide insight for me?
> 
> -Jason

Ray