DEV Community

Pavel Polívka
Pavel Polívka

Posted on

Simple bash timeout for operation

Recently I was writing bunch of automation scripts that were waiting for some file on a disk to appear.

I was in need of some kind of timeout if operation that would wait for few minutes for that file, and fail if that file will not appear.

As I like to do I set up to search something like on internet, unsuccessfully. So I wrote it myself.

TIMEOUT_MINUTES=10
WAIT_SECONDS=5
START=1
END=$((($TIMEOUT_MINUTES * 60) / $WAIT_SECONDS))

for i in $(seq $START $END); do
    if [  ! -f "/deploy/transfer_ok" ]
    then
        sleep $WAIT_SECONDS
    else
        break
    fi
done

if [  ! -f "/deploy/transfer_ok" ]
then
    echo "File transfer_ok not found."
    exit 1
fi

echo "Complete."
Enter fullscreen mode Exit fullscreen mode

Let's go over it to explain.

First few lines are basically our settings.
We want to wait up to 20 minutes, check each 5 seconds.
START and END will calculate how many tries we will do.

The for cycle will go over a sequence created from START and END. Every step will check if the file is not present on disk. If no it will sleep for the WAIT_SECONDS seconds. If so it will break the cycle.

After we are out of the loop, we will check one more time. If the file is still not present we will exit the script with error code.


If you want to see more like this you can follow me on Twitter.

Latest comments (0)