Re: bash error handling help
On 2005-06-04, theal wrote:
> I am have a script that uses a for loop to copy files to about 100 servers.
> I know how to get it to exit the entire script on an error, but I only want
> to stop what it is doing for the current $i and move to the next. here is
> the basics of the script. there may be some syntax errors in this script as
> I have edited it for public viewing.
>
> #!/bin/bash
>
> hostlist=`less /usr/local/src/client_hosts.txt|grep -v "#"|cut -d "," -f1`
Why are you using less? That's for interactive use; it's even worse
than cat. Just use the filename as an argument to grep:
hostlist=`grep -v "#" /usr/local/src/client_hosts.txt | cut -d "," -f1`
Or:
hostlist=`awk '!/#/ {print $1}' /usr/local/src/client_hosts.txt`
> if [ ! -f /usr/local/bin/myfile_client.sh ] ; then
> echo "/usr/local/bin/myfile_client.sh does not exist"
> exit 1
> fi
>
> function log()
> {
> echo [`date "+%Y-%m-%d %H:%M"`] $1
> echo [`date "+%Y-%m-%d %H:%M"`] $1 >> /usr/local/bin/myfile.log
> echo [`date "+%Y-%m-%d %H:%M"`] $1 >> /tmp/myfile.log
> }
>
> function run()
> {
> CMD=$1
>
> # Don't abort on errors
> set +e
> # Capture STDERR to ERR
> ERR=$($CMD 2>&1)
> # Capture return value from command
> RETVAL=$?
> # re-enable abort-on-err
> # set -e
>
> if [ "$ERR" ] ; then
> log "Error processing: $ERR"
> fi
>
> return $RETVAL
> }
Why did you include this function? You don't use it in your
example, but you use cleanup, and didn't include that.
> function errhandler()
> {
> log "Aborting abnormally..."
> cleanup
> }
>
> trap errhandler ERR
Why?
Why not just check that each command completes successfully?
If you don't want to exit on all errors, why install a trap that
does?
> for i in $hostlist
> do
> echo "determine if temp exits"
> if [ -f /tmp/temp ] ; then
> rm /tmp/temp
> elif [ -d /tmp/temp ] ; then
> rm -rf /tmp/temp
> fi
>
> echo "Creating client /tmp/temp directory"
> log "Creating client /tmp/temp directory"
> ssh -i ~/.ssh/$i me@$i "mkdir -p /tmp/temp/"
>
> echo "Transfering files to $i:/tmp/temp"
> log "Transfering files to $i:/tmp/temp"
> scp -i ~/.ssh/$i /usr/local/bin/myfile.sh me@$i:/tmp/temp
>
> echo "Executing myfile.sh"
> log "Executing myfile.sh"
> ssh -i ~/.ssh/$i me@$i "/tmp/temp/myfile.sh"
>
> echo "Removing client /tmp/temp"
> log "Removing client /tmp/temp"
> ssh -i ~/.ssh/$i me@$i "rm -rf /tmp/temp"
>
> echo "Finished $i myfile.sh "
> log "Finished $i myfile.sh "
> echo " "
> done
--
Chris F.A. Johnson <http://cfaj.freeshell.org>
==================================================================
Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
<http://www.torfree.net/~chris/books/cfaj/ssr.html>
Reply to: