Ben
Ben

Reputation: 305

Set a timeout limit when reading a file

I am trying to write a basic script that runs through a file line by line until a time limit is reached. Is there a way to stop the read -r line after x timelimit? I tried -t 10 for a 10 second limit. I also tried a while loop

From the man read -t only seems to be relevant for a timeout not a time limit

file.txt contains over 150000 lines of random characters separated by new lines

code attempt 1:

#!/bin/bash
file="./file.txt"
while IFS='' read -r -t 10 line ; do
    echo "$line"
done <"$file" #finished

code attempt 2:

#!/bin/bash
timelimit=10
file="./file.txt"
while [[ "$timelimit" -gt "0" ]] ; do
    sleep 1
    ((--timelimit))
    while IFS='' read -r line ; do
        echo "$line"
    done <"$file" #finished
done

code attempt 1 fails since it has no limiter (just a timeout set)

code attempt 2 fails since it runs the decrement then the next while loop and wont re-enter until it has finished a full loop (15000 lines)

Upvotes: 0

Views: 541

Answers (2)

chepner
chepner

Reputation: 531125

You can use the built-in variable SECONDS for rough control.

SECONDS=0  # reset the counter
file="./file.txt"
while ((SECONDS < 10) && IFS= read -r line ; do
    echo "$line"
done <"$file" #finished  

Assuming each read and the body of the loop doesn't take too long, the loop will exit very close to 10 seconds after it begins.

Upvotes: 1

rudicangiotti
rudicangiotti

Reputation: 566

Check out this possible solution, using date +%s:

CURRENT_DATE=$( date +%s )
END_DATE=$(( CURRENT_DATE+10 ))

while [ $CURRENT_DATE -le $END_DATE ];
do
    read -r LINE
    if [ $? -ne 0 ];
    then
        break
        #exit from loop if file is over...
    fi
    CURRENT_DATE=$( date +%s )
    #update CURRENT_DATE...
done

The above mentioned command returns the current date value in seconds from epoch (January 1st, 1970).

Upvotes: 3

Related Questions