Score:3

Script needs to be stopped after 24 hours

ec flag

I would like to run my script for 24 hrs, then it needs to be stopped even if processes are still going on.

Score:20
in flag

Use timeout:

timeout 24h my_script

Or use at to kill at a specific time, something like this:

my_script &
my_script_pid=$!

at 13:37 <<< "kill $my_script_pid"
# or
at now+24hours <<< "kill $my_script_pid"

# optional, if you want to close the terminal:
disown

Using at can have some benefits, e.g. when launching your script via ssh and detach from the current terminal (-> disown), you can close the connection / the terminal.
But you should be aware, that if the script stops before the time is up, the PID might get reused. You might be able to find the PID with other means, e.g. ps aux or pkill myscript.sh or so.

You could also use screen or nohup with the first command.

cobbal avatar
lc flag
Note that pids are eventually reused, so `at` being appropriate depends on the context in which it's running: https://unix.stackexchange.com/a/414974/5471
gustafc avatar
ck flag
There are no specific benefits to `at` when launching processes over ssh (or if you close the terminal), since the script would be terminated when the session is closed unless you start it with something like `nohup my_script`, but then you might just as well use `nohup timeout 86400 my_script` instead.
pLumo avatar
in flag
thanks fpr your comments, added the information.
d33tah avatar
br flag
For extra readability, consider replacing `86400` with `24h`.
pLumo avatar
in flag
Thanks, edited.
Score:4
jp flag

A few alternatives based on the fact that kill 0 signals all processes in the current process group.

For example:

sh -c './script & sleep 24h; kill 0'

Or:

./script | ( sleep 24h; kill 0 )

Or:

./script | { sleep 24h; kill 0; }
Score:-1
in flag

Can you use crontab to kill the service

#!/bin/bash
cat <(crontab -l) <(echo "0 0 0 0 0 kill-scripty.sh") | crontab -

# do something
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.