Home > Back-end >  How to stop the execution of a bash command after N seconds?
How to stop the execution of a bash command after N seconds?

Time:07-12

I am writing a simple bash script that analyses the contents of a directory and invokes a specific command for each file, however, in some cases, the execution takes longer than expected, and I would like to stop it after a certain number of seconds (or minutes) to move on to parsing the next entry.

For now, the script works in the following way:

#!/bin/bash
for f in /home/Users/Desktop/fdroid_tests/destination_dir/*; do
  if [ -d "$f" ]; then
     qark --java $f
  fi
done

How can I solve it?

CodePudding user response:

Besides just backgrounding the tasks, you may also be interested in the timeout command. For example timeout 5s qark --java $f will run your qark application and signal it to exit after 5 seconds if it hasn't already exited.

You can combine the two answers as well (timeout 5s qark --java $f &) if it's okay to have all your instances of qark run simultaneously. If you do, you may also want to add a wait after the loop so that the script doesn't exit until all the qark instances finish or timeout.

CodePudding user response:

In bash, it is possible to launch a process in background, using the ampersand switch:

qark --java $f &

You wait for five seconds:

sleep 5

You stop all running qark processes, using pkill:

pkill qark

(I didn't try this, but you can give it a try.)

Edit:
According to the added comments to this answer, this might even be better:

qark --java $f & pid=$!
sleep 5
kill $pid
  •  Tags:  
  • bash
  • Related