1

In my bash script I run a command that activates a script. I repeat this command many times in a for loop and as such want to wait until the script is finished before running it again. My bash script is as follows

for k in $(seq 1 5)
do
   sed_param='s/mu = .*/mu = '${mu}';/'
   sed -i "$sed_param" brusselator.c
   make brusselator.tst &
done

As far as I know the & at the end lets the script know to wait until the command is finished, but this isn't working. Is there some other way?

Furthermore, sometimes the command can take very very long, in this case I would maximally want to wait 5 seconds. But if the command is done earlier I would't want to wait 5 seconds. Is there some way to achieve this?

Caspertijmen1
  • 351
  • 1
  • 14
  • 1
    ‘_As far as I know the & at the end lets the script know to wait until the command is finished_’ No; it does the exact opposite. Waiting for a command to finish is the default, so just don’t use the `&`. – Biffen Sep 27 '21 at 11:40
  • 2
    To kill something after some time, you can look into the [`timeout`](https://www.gnu.org/software/coreutils/manual/html_node/timeout-invocation.html#timeout-invocation) command. – Benjamin W. Sep 27 '21 at 11:41
  • 2
    As for the timeout: How about [the `timeout` command](https://www.gnu.org/software/coreutils/manual/html_node/timeout-invocation.html#timeout-invocation)? – Biffen Sep 27 '21 at 11:41
  • 1
    This loop doesn't seem to make sense, is `$mu` being modified somewhere? As is, this is running the exact same commands 5 times, and sed won't actually be doing anything. – Benjamin W. Sep 27 '21 at 11:42
  • @BenjaminW. I have more loops so $mu is modified in another loop, but for just this example I only copied the inner loop ;) – Caspertijmen1 Sep 27 '21 at 11:48

1 Answers1

5

There is the timeout command. You would use it like

timeout -k 5 make brusselator.tst

Maybe you would like to see also if it exited successfully, failed or was killed because it timed out.

timeout -k 5 make brusselator.tst && echo OK || echo Failed, status $?

If the command times out, and --preserve-status is not set, then command exits with status 124. Different status would mean that make failed for different reason before timing out.

Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28