Konrad Konrad - 7 months ago 19
Bash Question

Creating while loop in bash that would run for specific time

I'm interested in creating a while loop in bash

(version: 3.2.57(1)-release)
running on that would run for a specific number of seconds/minutes.


For instance, I would like to create n files each with current date and time during the period of 5 seconds.


My loop structure would be fairly basic:

i=$cmd(date %ss)
j=$i + 10
while [ $i -lt $j ]
fileName=$cmd(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 32)
date > $fileName
i=date %ss


When I try to execute the script I get the following errors:

loop.sh: line 1: syntax error near unexpected token `('
loop.sh: line 1: `i=$cmd(date %ss)'

Desired results:

  • The
    counter reflects seconds, the loop stops after 10 seconds

  • Random
    files with current date as the sole content are created in the current working directory


The following will yield what you stated under "Desired results".


i="$(date +%s)"
j="$(( i + 10 ))"

while [ $i -lt $j ]; do
    fileName="$(cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 32)"
    date > "${fileName}.txt"
    i="$(date +%s)"