Home > Back-end >  Bash - kill a command after a certain time [duplicate]
Bash - kill a command after a certain time [duplicate]

Time:09-28

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?

CodePudding user response:

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.

  •  Tags:  
  • bash
  • Related