2

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
4
  • 3
    Try shellcheck.net first to clean up the syntax issues that don't require human feedback Commented Jun 21, 2016 at 21:50
  • @thatotherguy I tried and got another error, post updated. Commented Jun 21, 2016 at 21:54
  • 1
    Here's how to assigning command output to a variable: var=$(mycommand) e.g. var=$(date +%s) Commented Jun 21, 2016 at 22:27
  • @Konrad, SO is such a fast paced forum that I normally do much more reading of posts then answering, even if I know the answer the core group always post so fast I don't get a chance to. Anyway, while I was able to help you I wanted to say I learned something new with the method you chose to get the fileName and have added your technique to my code library. Thanks! Commented Jun 22, 2016 at 13:16

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.