Konrad Konrad - 5 months ago 14
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.

Example



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

Approach



My loop structure would be fairly basic:

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


Problem



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
    i
    counter reflects seconds, the loop stops after 10 seconds

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


Answer

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

#!/bin/bash

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)"
done