3

So simple a bash script which contains only two lines.

cat show.sh
systemctl status cron
exit  0 

Executed it with root in terminal.

bash  show.sh

All info about cron.service show on terminal.

cron.service - Regular background program processing daemon
   Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: ena
   Active: active (running) since Sat 2019-08-10 06:51:18 EDT; 13h ago
     Docs: man:cron(8)

Why the show.sh is not in exit status,to add a click on q will exit show.sh,why exit 0 not execute?how to trigger it?
My expection:show info about cron.service on terminal and exit show.sh script.
Half done for my show.sh,just show info about cron.service on terminal.
It is meaningful that a long script automate a job ,the above two lines is the last step to show the whole script's status.

showkey
  • 482
  • 42
  • 140
  • 295
  • `exit` is not run until `systemctl` finished. If `systemctl status cron` is waiting for you to press `q`, then, well, there's your answer. – Charles Duffy Aug 11 '19 at 00:57
  • ...if you don't want systemctl to do that, I'd suggest adjusting its settings to no longer launch a pager. – Charles Duffy Aug 11 '19 at 00:58
  • 1
    BTW, I would suggest leaving out the `exit 0` line. If you don't have it, the script exits with the status of the last command it ran (that is, the default behavior is `echo "$?"`), which is useful: It passes through the exit status of `systemctl`, so your script's caller knows that result. – Charles Duffy Aug 11 '19 at 01:01
  • (err, I meant `exit "$?"`, not `echo "$?"`, of course). – Charles Duffy Apr 29 '20 at 16:28

1 Answers1

6

Pass --no-pager to systemctl, as follows:

systemctl --no-pager status cron

Otherwise, systemctl runs less (or a program like it), which doesn't exit until q is pressed; consequently, control isn't directly handed back to your script.


See the related question on our sister site Unix & Linux at Can I prevent service foo status from paging its output through less?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441