Dayne
Dayne

Reputation: 33

How to run a bash script for a certain amount of time?

I want my script to run for a certain amount of time, just like this:

timeout 10s ./script

However, I want to integrate the command within my script

for a in {a..z};
do
  for b in {a..z};
  do
  echo "$a$b"
  done
done

I've tried putting the timeout command in the for loop, but it doesn't work. How do use the timeout command in the script?

Upvotes: 1

Views: 1001

Answers (2)

sjsam
sjsam

Reputation: 21965

timeout 2s bash -c 'for a in {a..z};
do
  for b in {a..z};
  do
  echo "$a$b"
  done
done'

is one way to do it but as @karafka already mentioned you can avoid for loop by doing

timeout 2s echo {a..z}{a..z} | sed 's/[[:blank:]]/\n/g'

or even

timeout 2s printf "%s\n" {a..z}{a..z}

Upvotes: 2

Eric
Eric

Reputation: 1521

You can use a background process and your own timer. It's not guaranteed to last exactly 10 seconds, but it will usually be close.

for a in {a..z};
do
  for b in {a..z};
  do
  echo "$a$b"
  done
done &
sleep 10;
kill ${!}

Upvotes: 0

Related Questions