Killing a bash process and running the second part of script

I want to run a script that calls remote ssh and if it gets hung, I want to be able to kill that part of the script and run another command in the script

for example I have a statement like this:

if [[ $nbserve == SENDone || $nbserve == Zray|| $nbserve == Partition ]]; 
then 
    export tapes=$(for tape in $(su - nacct -c 'ssh remote1 "cat /filer/cart/vol0/tech/File\ Lists/'"$nbserve"'/'"$move"'"'| gawk '{print $1}'|sed -n '/\([0-9]\)\(.*\)/p'); 
    do echo $cartridge;done);
else 
    export cartridges=$(for cartridge in $(su - nbacct -c 'ssh remote1 "cat /filer/cart/vol0/techFile\ Lists/'"$nbserve"'/'"$movelist"'"'| tr -d " \t" |sed -n 's/\(.*)\)\([A-Z]\{1,3\}[0-9]\{1,5\}\)\(.*\)/\2/p'); 
    do echo $cartridge;done);
fi

90% of the time this command works, but sometimes the nbserv name is not accessible this way (by ssh). In that case, I'd like to run another command that uses another syntax.

Is there a way to terminate the above statement if it hangs, and then proceed to move to the next portion of the script to run another command?
Something like a kill process command. But then how would the script go to another line? Is it possible?

Let's take this one run-on one liner and make it usable. Cramming stuff into one
line may be cool but it prevents doing what you want.

    # old 
    export tapes=$(for tape in $(su - nacct -c 'ssh remote1 "cat /filer/cart/vol0/tech/File\ Lists/'"$nbserve"'/'"$move"'"'| gawk '{print $1}'|sed -n '/\([0-9]\)\(.*\)/p'); 
    do echo $cartridge;done);
    myfile="/filer/cart/vol0/tech/File\ Lists/$nbserve/$move"
    # many ssh calls hang change this prt to check for completion
    # Instead of many ssh calls copy the file locally.
    (su - nacct -c "scp remote:${myfile} /tmp/tmp1" ) &
    pid=$!    # pid of child scp process
    sleep 5
    kill -0 $pid
    if [ $? -eq 0 ] ; then
      kill $pid   # get rid the child process
      wait
      # we are hung up so execute some other lines here
    else
      # if we did not get hung up then run gawk on the local file /tmp/tmp1
      # here.
      tapes=$( #your gawk/sed goes here using /tmp/tmp1 # )
    fi

The concept is to use return codes to get the child pid, sleep a while,
then check the pid. If you were to sleep 5 between all of your for loop
calls this could take forever. So, we lost the loop. If you like loops you
can run it AFTER the one ssh(scp) call.

1 Like