2

Let's say we have "for loop" as follow:

#!/bin/bash
for i in $(cat test_file); do 
echo $i
done

The content of text file is names of folders in a parent folder

If the text_file contains 10000 entries (i.e. variable i), how can I tell "for loop" to sleep 10 seconds between every 10 "echos". In other words when for loop reads the variable i in the text_file how can I control the number of variables that for loop can run every specific period of time? So the output as follow:

   Variable #1
   Variable #2
   Variable #3
   .
   .
   .
   .
   sleep 10
    Variable #11
    Variable #12
    Variable #13
   .
   .       .
  • count the iterations and see when dividing by ten results in a whole number; when that condition exist (mod 10) you simply thread sleep for 10 seconds. – Micah LaCombe Apr 26 '17 at 20:25
  • 1
    What are you trying to accomplish ? – don_crissti Apr 26 '17 at 20:51
  • for i in 1 2 3; do stuff; done waits for stuff to complete on each iteration so not sure how they would "work at the same time"... oh well... – don_crissti Apr 26 '17 at 21:33
  • @ don_crissti. Thank you! This approach is very helpful if you want to apply a bunch of commands on a very large number of images. (i.e. you put the commands between two brackets as follow (command 1; command 2 command 3 ... etc )&. This will apply all the commands on all the images at once. In order to avoid "out of memory" I like how the approach bellow controlled the resources. – user88036 Apr 27 '17 at 18:52
6

Use the following bash script (to sleep 10 seconds between every 10 "echos"):

test.sh is a test name of the script

#!/bin/bash
while ((++i)); read -r line
do
    echo "$line"
    if (( "$i" % 10 == 0)) 
    then
        sleep 10
    fi
done < $1

Usage:

bash test.sh test_file

while ((++i)) - will increment i counter each time when read -r line returns a line from the input

if (( "$i" % 10 == 0)) - checks if current line number i is divisible by 10 (means that the execution flow reaches next 10 lines)

sleep 10 - pauses the script for 10 seconds

-1
xargs -L 10 sh -c 'printf "%s\n" "$@"; sleep 10' sh < test_file

Working

  • xargs with -L will take 10 lines in one go and pass them on to sh -c command. There the first argument is consumed as name of program, we will place a dummy name sh. Then these 10 lines will be available to sh as "$@" and we can do whatever we want. Here we just print them. Then we sleep for 10 secs. After that xargs shall pass on the next 10 tranche and this cycle repeats till it runs out of lies in test_file.
  • @heemayl I am sorry for not giving any workings of the code. Updated. – user218374 Apr 27 '17 at 3:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy