ygoe
ygoe

Reputation: 20364

Start systemctl from a Bash script and don't wait for it

I need to call systemctl start myservice near the end of a Bash script, but I really don't care about whether it will be successful or when it intends to return. I just need to start the action. It's others' task to monitor the status of that service. My script should return as quickly as possible, no matter whether that service has completed starting, I'm not depending on that.

My first thought was to use something like this:

# do other work
systemctl start myservice &
echo "done"
# end of script

But I've read that this is problematic with signals or in non-interactive environments, where my script is usually called. So I read on and found the nohup command, but that seems to write output files anywhere and might hang if you don't redirect stdin from /dev/null, they say.

So I still don't know how to do this correctly. I'm open for a generic way to start-and-forget any process from a Bash script, or for systemctl specifically as this will be my only use case for now.

Upvotes: 6

Views: 9083

Answers (2)

ygoe
ygoe

Reputation: 20364

I found a pretty easy solution to this:

systemctl start --no-block myservice

The --no-block option can be used for starting, stopping etc. and it won't wait for the actual process to finish. More details in the manpage of systemctl.

Upvotes: 13

David C. Rankin
David C. Rankin

Reputation: 84531

If you simply want to start systemctl and you don't want to wait for it, use exec to replace the current process with the systemctl call. For example, instead of backgrounding the process, simply use:

exec systemctl ....

You may want to include the --no-pager option to ensure that the process isn't piped to a pager which would block waiting for user input, e.g.

exec systemctl --no-pager ....

Of course your echo "done" will never be reached, but that wasn't pertinent to your script.

Upvotes: 1

Related Questions