1

I'm trying to run a for loop inside of bash -c so I can time it. This code writes 23 every time. How can I make it iterate through the numbers?

time bash -c "for i in {0..23}; do echo $i & done"

This code works, but I need to time the whole operation:

for i in {0..23}; do echo $i & done

The echo command is just for simplicity. I am really trying to run dd, that's why I background the process with &

1 Answer 1

7

There are two issues.

time bash -c "for i in {0..23}; do echo $i & done"

doesn’t work as you expect because $i is expanded immediately; you need to use single quotes:

time bash -c 'for i in {0..23}; do echo $i & done'

To get time to wait for all the background jobs, you can use wait:

time bash -c 'for i in {0..23}; do sleep $i & done; wait'

This causes the shell to wait for all its jobs to finish, which results in time measuring the time taken for all the operations together.

1
  • Thank you! That makes sense Commented Oct 3, 2019 at 22:16

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.