[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

bash error handling help



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.

Thanks

Tony



#!/bin/bash

hostlist=`less /usr/local/src/client_hosts.txt|grep -v "#"|cut -d "," -f1`

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
}

function errhandler()
{
    log "Aborting abnormally..."
    cleanup
}

trap errhandler ERR


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





Reply to: