[CentOS] Bash Script help...

Fri May 8 05:50:22 UTC 2009
Les Mikesell <lesmikesell at gmail.com>

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.

A few commands can be stuck together in the cron command.  Separating 
them with ';'' makes them execute sequentially regardless of status; 
separating with '&&' will continue only if the previous command 
succeeds.  For more than a few, put the commands in a script file

> 
> Example:
> 
> cd /system_backups/
> 
> tar cvf apache-conf.tar /etc/httpd/conf/*
> gzip -v9 apache-conf.tar

I'd:
cd /etc/httpd/conf && tar -czvf /system_backups/apache-conf.tar.gz
instead.

> 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?

Commands in a script execute sequentially unless you explicitly use an & 
to put them in the background.

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

Each command will return a status in the $? variable that you can check. 
  The shell philosophy is that there are lots of ways to fail but 
usually only one way to succeed, so the value 0 represents success, 
anything else is failure.  You can use the 'test' operator (usually 
written as [, but read the test man page to see what it does), or just:
command1 && command2   (runs command2 only if command1 succeeds)
command1 || command2   (runs command2 only if command1 fails - you can 
exit this way)

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

Yes, cron will automatically mail any output to the user that owns the 
cron job.  Just add an alias for this local user (probably root) to make 
it go where you want.

> 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?

Use ssh keys instead.

> 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?

You'd probably be better off running something like backuppc 
(http://backuppc.sourceforge.net/) instead of rolling your own.  And you 
might want some kind of version control system like subversion for your 
content and most important configuration files.

--
     Les Mikesell
        lesmikesell at gmail.com