Wait for a file in bash

Sometimes your bash script needs to wait for a file to exist before proceeding. Here is one way to do it.

function wait_till_exists {
    file=$1
    timeout=${2:-60}
    counter=1
    until ls -l $file &> /dev/null
    do
        if [ $counter -gt $timeout ]; then
            return 1
        fi
        sleep 1
        ((counter++))
    done
    return 0
}

wait_for_file="/tmp/myfile"
if ! wait_till_exists "$wait_for_file" 5; then
    echo Timed out waiting for $wait_for_file to exist
exit 1
fi

echo "$wait_for_file found"
Wait for a file in bash

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s