Bash script for periodically launching and killing an app

I have a short script which should launch an app, wait for an hour, then kill it and wait for a minute. It only starts the app. I tried to run the script both as a normal user and root, but nothing helped.

while (true); do ./app sleep 3600 pkill -f app sleep 60
done
2

2 Answers

The problem is that all commands are executed from the first line to the last in order. So as @Scott Stensland mentoined you have to put it into background via & (ampersand) to make the timer start.

And furthermore I think getting the PID of your app via searching through process names is a dangerous practice since you might accidentally kill a program which contains the string app in its name. So a safer way is to use the variable ! to get the PID . So your modified script should now looks like this :

while (true); do ./app & app_pid=$! sleep 3600 kill $app_pid sleep 60
done

When you put a process into background via & it goes into the job list of the parent bash process , and via ! you can get the PID of the last job.So it's safe.

You could consider using the timeout command:

NAME timeout - run a command with a time limit
SYNOPSIS timeout [OPTION] DURATION COMMAND [ARG]... timeout [OPTION]
DESCRIPTION Start COMMAND, and kill it if still running after DURATION.

ex.

#!/bin/bash
while :
do timeout 1h ./app sleep 1m
done

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like