user2786484
user2786484

Reputation: 101

Bash script for do loop that detects a time period elapsed and then continues

I have a script that runs through a list of servers to connect to and grabs by SCP over files to store

Occasionally due to various reasons one of the servers crashes and my script gets stuck for around 4 hours before moving on through the list.

I would like to be able to detect a connection issue or a period of time elapsed after script has started and kill that command and move on to next.

I suspect that this would involve a wait or sleep and continue but I am new to loops and bash

#!/bin/bash
#
# Generate a list of backups to grab
df|grep backups|awk -F/ '{ print $NF }'>/tmp/backuplistsmb

# Get each backup in turn

for BACKUP in `cat /tmp/backuplistsmb`
do
        cd /srv/backups/$BACKUP
        scp -o StrictHostKeyChecking=no $BACKUP:* .
sleep 3h
done

The above script works fine but does get stuck for 4 hours should there be a connection issue. It is worth noting that some of the transfers take 10 mins and some 2.5 hours

Any ideas or help would very appreciated

Upvotes: 1

Views: 340

Answers (1)

quantummind
quantummind

Reputation: 2136

Try to use the timeout program for that:

Usage:

timeout [OPTION] DURATION COMMAND [ARG]...

E.g. time (timeout 3 sleep 5) will run for 3 secs. So in your code you can use:

timeout 300 scp -o StrictHostKeyChecking=no $BACKUP:* .

This limits the copy to 5 minutes.

Upvotes: 1

Related Questions