The “proper” way to test if a service is running in a script The 2019 Stack Overflow Developer Survey Results Are Ingrep breaks formatting of systemctlProper way to add a user account via bash scriptDebian and Systemd: breaking ordering cycle errorYocto linux service script problemYocto systemd service script problemDebian 8 Jessie with OpenVPN clientMinecraft server startup/shutdown with systemd“Proper” way to run shell script as a daemonWhat is the “proper way” with to create a systemd service on a mounted (not booted) system?Proper way to use OnFailure in systemdRecommended way of checking only one running service?

Inverse Relationship Between Precision and Recall

Correct punctuation for showing a character's confusion

Is it a good practice to use a static variable in a Test Class and use that in the actual class instead of Test.isRunningTest()?

Is it ethical to upload a automatically generated paper to a non peer-reviewed site as part of a larger research?

Button changing its text & action. Good or terrible?

Accepted by European university, rejected by all American ones I applied to? Possible reasons?

How to obtain a position of last non-zero element

Why isn't the circumferential light around the M87 black hole's event horizon symmetric?

Dynamic substitution of variables in bash

Why not take a picture of a closer black hole?

How to notate time signature switching consistently every measure

If my opponent casts Ultimate Price on my Phantasmal Bear, can I save it by casting Snap or Curfew?

Mathematics of imaging the black hole

What is the meaning of Triage in Cybersec world?

Are spiders unable to hurt humans, especially very small spiders?

Geography at the pixel level

Is it okay to consider publishing in my first year of PhD?

Can an undergraduate be advised by a professor who is very far away?

What information about me do stores get via my credit card?

Is it ok to offer lower paid work as a trial period before negotiating for a full-time job?

How to charge AirPods to keep battery healthy?

Output the Arecibo Message

Is it possible for absolutely everyone to attain enlightenment?

Did Scotland spend $250,000 for the slogan "Welcome to Scotland"?



The “proper” way to test if a service is running in a script



The 2019 Stack Overflow Developer Survey Results Are Ingrep breaks formatting of systemctlProper way to add a user account via bash scriptDebian and Systemd: breaking ordering cycle errorYocto linux service script problemYocto systemd service script problemDebian 8 Jessie with OpenVPN clientMinecraft server startup/shutdown with systemd“Proper” way to run shell script as a daemonWhat is the “proper way” with to create a systemd service on a mounted (not booted) system?Proper way to use OnFailure in systemdRecommended way of checking only one running service?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








67















My problem:



I'm writing a bash script and in it I'd like to check if a given service is running.



I know how to do this manually, with $ service [service_name] status.



But (especially since the move to systemd) that prints a whole bunch of text that's a little messy to parse. I assumed there's a command made for scripts with simple output or a return value I can check.



But Googling around only yields a ton of "Oh, just ps aux | grep -v grep | grep [service_name]" results. That can't be the best practice, is it? What if another instance of that command is running, but not one started by the SysV init script?



Or should I just shut up and get my hands dirty with a little pgrep?










share|improve this question






























    67















    My problem:



    I'm writing a bash script and in it I'd like to check if a given service is running.



    I know how to do this manually, with $ service [service_name] status.



    But (especially since the move to systemd) that prints a whole bunch of text that's a little messy to parse. I assumed there's a command made for scripts with simple output or a return value I can check.



    But Googling around only yields a ton of "Oh, just ps aux | grep -v grep | grep [service_name]" results. That can't be the best practice, is it? What if another instance of that command is running, but not one started by the SysV init script?



    Or should I just shut up and get my hands dirty with a little pgrep?










    share|improve this question


























      67












      67








      67


      17






      My problem:



      I'm writing a bash script and in it I'd like to check if a given service is running.



      I know how to do this manually, with $ service [service_name] status.



      But (especially since the move to systemd) that prints a whole bunch of text that's a little messy to parse. I assumed there's a command made for scripts with simple output or a return value I can check.



      But Googling around only yields a ton of "Oh, just ps aux | grep -v grep | grep [service_name]" results. That can't be the best practice, is it? What if another instance of that command is running, but not one started by the SysV init script?



      Or should I just shut up and get my hands dirty with a little pgrep?










      share|improve this question
















      My problem:



      I'm writing a bash script and in it I'd like to check if a given service is running.



      I know how to do this manually, with $ service [service_name] status.



      But (especially since the move to systemd) that prints a whole bunch of text that's a little messy to parse. I assumed there's a command made for scripts with simple output or a return value I can check.



      But Googling around only yields a ton of "Oh, just ps aux | grep -v grep | grep [service_name]" results. That can't be the best practice, is it? What if another instance of that command is running, but not one started by the SysV init script?



      Or should I just shut up and get my hands dirty with a little pgrep?







      shell-script systemd






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 7 '17 at 13:24









      don_crissti

      52k15141168




      52k15141168










      asked Oct 7 '17 at 6:53









      Nick SNick S

      449147




      449147




















          6 Answers
          6






          active

          oldest

          votes


















          103














          systemctl has an is-active subcommand for this:



          systemctl is-active --quiet service


          will exit with status zero if service is active, non-zero otherwise, making it ideal for scripts:



          systemctl is-active --quiet service && echo Service is running


          If you omit --quiet it will also output the current status to its standard output.



          As pointed out by don_crissti, some units can be active even though nothing is running to provide the service: units marked as “RemainAfterExit” are considered active if they exit successfully, the idea being that they provide a service which doesn’t need a daemon (e.g. they configure some aspect of the system). Units involving daemons will however only be active if the daemon is still running.






          share|improve this answer
































            23














            systemctl does have a mode suitable for scripting; use show rather than status, and add the -p / --properties and --value options to get only the output you want.



            Here's an example (from an Ubuntu 17.04 system):



            $ systemctl show -p SubState --value NetworkManager
            running


            Running (or otherwise) is a SubState. If you want to know whether a service is active, use the property ActiveState



            $ systemctl show -p ActiveState --value x11-common
            inactive
            $ systemctl show -p SubState --value x11-common
            dead


            Notes from the man:



            show [PATTERN...|JOB...]
            Show properties of one or more units, jobs, or the manager
            itself. If no argument is specified, properties of the
            manager will be shown. If a unit name is specified, properties
            of the unit are shown, and if a job ID is specified,
            properties of the job are shown. By default, empty properties
            are suppressed. Use --all to show those too. To select specific
            properties to show, use --property=. This command is intended
            to be used whenever computer-parsable output is required. Use
            status if you are looking for formatted human-readable output.

            -p, --property=
            When showing unit/job/manager properties with the show command,
            limit display to properties specified in the argument. The
            argument should be a comma-separated list of property names,
            such as "MainPID". Unless specified, all known properties are
            shown. If specified more than once, all properties with the
            specified names are shown. Shell completion is implemented for
            property names.

            --value
            When printing properties with show, only print the value, and
            skip the property name and "=".





            share|improve this answer




















            • 2





              +1 for sophisticated answer . kindly specify the distros which will accept --version option with systemctl.

              – S.K. Venkat
              Apr 26 '18 at 11:31



















            9














            As a complement to Zanna's answer, the --value option for systemctl show has been introduced with version 230 of systemd. So it may not be available on certain distros like debian jessie.



            In this case, one can emulate the option by using sed:



            $ systemctl show -p ActiveState sshd | sed 's/ActiveState=//g'
            active
            $ systemctl show -p SubState sshd | sed 's/SubState=//g'
            running





            share|improve this answer


















            • 1





              +1 for pointed out the --value intro version & distro which will not work.

              – S.K. Venkat
              Apr 26 '18 at 11:29


















            2














            Instead of using the sed command like in the answer of Oxmel, it is enough to use cut -d'=' -f 2 for all kind of properties queried:



            for example:



            $ systemctl show -p ActiveState sshd | cut -d'=' -f2
            active
            $ systemctl show -p SubState sshd | cut -d'=' -f2
            running





            share|improve this answer
































              1














              i find this useful for command line execution or if you are making scripts.



              Copied from @StephenKitt



              This will check if the service is down and perform service restart



              systemctl is-active --quiet <service name> || <service name> restart


              the || there checks if the return value from systemctl is non-zero meaning if it's not active as explained by the author.






              share|improve this answer






























                0
















                I am too late to the party , however using systemctl is-active along with && and || to this in script wont be the case all the time. The below is one I used for tomcat but can use it in method taking arguments and pass service name as arguments if u have to check multiple services but its out of scope here.



                STATUS=`systemctl is-active tomcat.service`
                if [[ $STATUS == 'active' ]]; then
                echo "Execute your tasks ....."
                else
                echo " Service not running.... so exiting "
                exit 1
                fi


                This is how I made use of.... Just sharing mine.



                and for the simplicity and easy stuffs, follow others explained here :



                systemctl -q is-active tomcat.service && echo "Tomcat Runnung" || echo "Service is not running at all "





                share|improve this answer























                  Your Answer








                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "106"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: false,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: null,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f396630%2fthe-proper-way-to-test-if-a-service-is-running-in-a-script%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  103














                  systemctl has an is-active subcommand for this:



                  systemctl is-active --quiet service


                  will exit with status zero if service is active, non-zero otherwise, making it ideal for scripts:



                  systemctl is-active --quiet service && echo Service is running


                  If you omit --quiet it will also output the current status to its standard output.



                  As pointed out by don_crissti, some units can be active even though nothing is running to provide the service: units marked as “RemainAfterExit” are considered active if they exit successfully, the idea being that they provide a service which doesn’t need a daemon (e.g. they configure some aspect of the system). Units involving daemons will however only be active if the daemon is still running.






                  share|improve this answer





























                    103














                    systemctl has an is-active subcommand for this:



                    systemctl is-active --quiet service


                    will exit with status zero if service is active, non-zero otherwise, making it ideal for scripts:



                    systemctl is-active --quiet service && echo Service is running


                    If you omit --quiet it will also output the current status to its standard output.



                    As pointed out by don_crissti, some units can be active even though nothing is running to provide the service: units marked as “RemainAfterExit” are considered active if they exit successfully, the idea being that they provide a service which doesn’t need a daemon (e.g. they configure some aspect of the system). Units involving daemons will however only be active if the daemon is still running.






                    share|improve this answer



























                      103












                      103








                      103







                      systemctl has an is-active subcommand for this:



                      systemctl is-active --quiet service


                      will exit with status zero if service is active, non-zero otherwise, making it ideal for scripts:



                      systemctl is-active --quiet service && echo Service is running


                      If you omit --quiet it will also output the current status to its standard output.



                      As pointed out by don_crissti, some units can be active even though nothing is running to provide the service: units marked as “RemainAfterExit” are considered active if they exit successfully, the idea being that they provide a service which doesn’t need a daemon (e.g. they configure some aspect of the system). Units involving daemons will however only be active if the daemon is still running.






                      share|improve this answer















                      systemctl has an is-active subcommand for this:



                      systemctl is-active --quiet service


                      will exit with status zero if service is active, non-zero otherwise, making it ideal for scripts:



                      systemctl is-active --quiet service && echo Service is running


                      If you omit --quiet it will also output the current status to its standard output.



                      As pointed out by don_crissti, some units can be active even though nothing is running to provide the service: units marked as “RemainAfterExit” are considered active if they exit successfully, the idea being that they provide a service which doesn’t need a daemon (e.g. they configure some aspect of the system). Units involving daemons will however only be active if the daemon is still running.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Apr 4 '18 at 16:08









                      Cristian Ciupitu

                      2,10911722




                      2,10911722










                      answered Oct 7 '17 at 7:52









                      Stephen KittStephen Kitt

                      181k25414492




                      181k25414492























                          23














                          systemctl does have a mode suitable for scripting; use show rather than status, and add the -p / --properties and --value options to get only the output you want.



                          Here's an example (from an Ubuntu 17.04 system):



                          $ systemctl show -p SubState --value NetworkManager
                          running


                          Running (or otherwise) is a SubState. If you want to know whether a service is active, use the property ActiveState



                          $ systemctl show -p ActiveState --value x11-common
                          inactive
                          $ systemctl show -p SubState --value x11-common
                          dead


                          Notes from the man:



                          show [PATTERN...|JOB...]
                          Show properties of one or more units, jobs, or the manager
                          itself. If no argument is specified, properties of the
                          manager will be shown. If a unit name is specified, properties
                          of the unit are shown, and if a job ID is specified,
                          properties of the job are shown. By default, empty properties
                          are suppressed. Use --all to show those too. To select specific
                          properties to show, use --property=. This command is intended
                          to be used whenever computer-parsable output is required. Use
                          status if you are looking for formatted human-readable output.

                          -p, --property=
                          When showing unit/job/manager properties with the show command,
                          limit display to properties specified in the argument. The
                          argument should be a comma-separated list of property names,
                          such as "MainPID". Unless specified, all known properties are
                          shown. If specified more than once, all properties with the
                          specified names are shown. Shell completion is implemented for
                          property names.

                          --value
                          When printing properties with show, only print the value, and
                          skip the property name and "=".





                          share|improve this answer




















                          • 2





                            +1 for sophisticated answer . kindly specify the distros which will accept --version option with systemctl.

                            – S.K. Venkat
                            Apr 26 '18 at 11:31
















                          23














                          systemctl does have a mode suitable for scripting; use show rather than status, and add the -p / --properties and --value options to get only the output you want.



                          Here's an example (from an Ubuntu 17.04 system):



                          $ systemctl show -p SubState --value NetworkManager
                          running


                          Running (or otherwise) is a SubState. If you want to know whether a service is active, use the property ActiveState



                          $ systemctl show -p ActiveState --value x11-common
                          inactive
                          $ systemctl show -p SubState --value x11-common
                          dead


                          Notes from the man:



                          show [PATTERN...|JOB...]
                          Show properties of one or more units, jobs, or the manager
                          itself. If no argument is specified, properties of the
                          manager will be shown. If a unit name is specified, properties
                          of the unit are shown, and if a job ID is specified,
                          properties of the job are shown. By default, empty properties
                          are suppressed. Use --all to show those too. To select specific
                          properties to show, use --property=. This command is intended
                          to be used whenever computer-parsable output is required. Use
                          status if you are looking for formatted human-readable output.

                          -p, --property=
                          When showing unit/job/manager properties with the show command,
                          limit display to properties specified in the argument. The
                          argument should be a comma-separated list of property names,
                          such as "MainPID". Unless specified, all known properties are
                          shown. If specified more than once, all properties with the
                          specified names are shown. Shell completion is implemented for
                          property names.

                          --value
                          When printing properties with show, only print the value, and
                          skip the property name and "=".





                          share|improve this answer




















                          • 2





                            +1 for sophisticated answer . kindly specify the distros which will accept --version option with systemctl.

                            – S.K. Venkat
                            Apr 26 '18 at 11:31














                          23












                          23








                          23







                          systemctl does have a mode suitable for scripting; use show rather than status, and add the -p / --properties and --value options to get only the output you want.



                          Here's an example (from an Ubuntu 17.04 system):



                          $ systemctl show -p SubState --value NetworkManager
                          running


                          Running (or otherwise) is a SubState. If you want to know whether a service is active, use the property ActiveState



                          $ systemctl show -p ActiveState --value x11-common
                          inactive
                          $ systemctl show -p SubState --value x11-common
                          dead


                          Notes from the man:



                          show [PATTERN...|JOB...]
                          Show properties of one or more units, jobs, or the manager
                          itself. If no argument is specified, properties of the
                          manager will be shown. If a unit name is specified, properties
                          of the unit are shown, and if a job ID is specified,
                          properties of the job are shown. By default, empty properties
                          are suppressed. Use --all to show those too. To select specific
                          properties to show, use --property=. This command is intended
                          to be used whenever computer-parsable output is required. Use
                          status if you are looking for formatted human-readable output.

                          -p, --property=
                          When showing unit/job/manager properties with the show command,
                          limit display to properties specified in the argument. The
                          argument should be a comma-separated list of property names,
                          such as "MainPID". Unless specified, all known properties are
                          shown. If specified more than once, all properties with the
                          specified names are shown. Shell completion is implemented for
                          property names.

                          --value
                          When printing properties with show, only print the value, and
                          skip the property name and "=".





                          share|improve this answer















                          systemctl does have a mode suitable for scripting; use show rather than status, and add the -p / --properties and --value options to get only the output you want.



                          Here's an example (from an Ubuntu 17.04 system):



                          $ systemctl show -p SubState --value NetworkManager
                          running


                          Running (or otherwise) is a SubState. If you want to know whether a service is active, use the property ActiveState



                          $ systemctl show -p ActiveState --value x11-common
                          inactive
                          $ systemctl show -p SubState --value x11-common
                          dead


                          Notes from the man:



                          show [PATTERN...|JOB...]
                          Show properties of one or more units, jobs, or the manager
                          itself. If no argument is specified, properties of the
                          manager will be shown. If a unit name is specified, properties
                          of the unit are shown, and if a job ID is specified,
                          properties of the job are shown. By default, empty properties
                          are suppressed. Use --all to show those too. To select specific
                          properties to show, use --property=. This command is intended
                          to be used whenever computer-parsable output is required. Use
                          status if you are looking for formatted human-readable output.

                          -p, --property=
                          When showing unit/job/manager properties with the show command,
                          limit display to properties specified in the argument. The
                          argument should be a comma-separated list of property names,
                          such as "MainPID". Unless specified, all known properties are
                          shown. If specified more than once, all properties with the
                          specified names are shown. Shell completion is implemented for
                          property names.

                          --value
                          When printing properties with show, only print the value, and
                          skip the property name and "=".






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Aug 23 '18 at 18:37









                          Alexis Wilke

                          1,071718




                          1,071718










                          answered Oct 7 '17 at 7:15









                          ZannaZanna

                          2,6261224




                          2,6261224







                          • 2





                            +1 for sophisticated answer . kindly specify the distros which will accept --version option with systemctl.

                            – S.K. Venkat
                            Apr 26 '18 at 11:31













                          • 2





                            +1 for sophisticated answer . kindly specify the distros which will accept --version option with systemctl.

                            – S.K. Venkat
                            Apr 26 '18 at 11:31








                          2




                          2





                          +1 for sophisticated answer . kindly specify the distros which will accept --version option with systemctl.

                          – S.K. Venkat
                          Apr 26 '18 at 11:31






                          +1 for sophisticated answer . kindly specify the distros which will accept --version option with systemctl.

                          – S.K. Venkat
                          Apr 26 '18 at 11:31












                          9














                          As a complement to Zanna's answer, the --value option for systemctl show has been introduced with version 230 of systemd. So it may not be available on certain distros like debian jessie.



                          In this case, one can emulate the option by using sed:



                          $ systemctl show -p ActiveState sshd | sed 's/ActiveState=//g'
                          active
                          $ systemctl show -p SubState sshd | sed 's/SubState=//g'
                          running





                          share|improve this answer


















                          • 1





                            +1 for pointed out the --value intro version & distro which will not work.

                            – S.K. Venkat
                            Apr 26 '18 at 11:29















                          9














                          As a complement to Zanna's answer, the --value option for systemctl show has been introduced with version 230 of systemd. So it may not be available on certain distros like debian jessie.



                          In this case, one can emulate the option by using sed:



                          $ systemctl show -p ActiveState sshd | sed 's/ActiveState=//g'
                          active
                          $ systemctl show -p SubState sshd | sed 's/SubState=//g'
                          running





                          share|improve this answer


















                          • 1





                            +1 for pointed out the --value intro version & distro which will not work.

                            – S.K. Venkat
                            Apr 26 '18 at 11:29













                          9












                          9








                          9







                          As a complement to Zanna's answer, the --value option for systemctl show has been introduced with version 230 of systemd. So it may not be available on certain distros like debian jessie.



                          In this case, one can emulate the option by using sed:



                          $ systemctl show -p ActiveState sshd | sed 's/ActiveState=//g'
                          active
                          $ systemctl show -p SubState sshd | sed 's/SubState=//g'
                          running





                          share|improve this answer













                          As a complement to Zanna's answer, the --value option for systemctl show has been introduced with version 230 of systemd. So it may not be available on certain distros like debian jessie.



                          In this case, one can emulate the option by using sed:



                          $ systemctl show -p ActiveState sshd | sed 's/ActiveState=//g'
                          active
                          $ systemctl show -p SubState sshd | sed 's/SubState=//g'
                          running






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Apr 3 '18 at 15:59









                          OxmelOxmel

                          9113




                          9113







                          • 1





                            +1 for pointed out the --value intro version & distro which will not work.

                            – S.K. Venkat
                            Apr 26 '18 at 11:29












                          • 1





                            +1 for pointed out the --value intro version & distro which will not work.

                            – S.K. Venkat
                            Apr 26 '18 at 11:29







                          1




                          1





                          +1 for pointed out the --value intro version & distro which will not work.

                          – S.K. Venkat
                          Apr 26 '18 at 11:29





                          +1 for pointed out the --value intro version & distro which will not work.

                          – S.K. Venkat
                          Apr 26 '18 at 11:29











                          2














                          Instead of using the sed command like in the answer of Oxmel, it is enough to use cut -d'=' -f 2 for all kind of properties queried:



                          for example:



                          $ systemctl show -p ActiveState sshd | cut -d'=' -f2
                          active
                          $ systemctl show -p SubState sshd | cut -d'=' -f2
                          running





                          share|improve this answer





























                            2














                            Instead of using the sed command like in the answer of Oxmel, it is enough to use cut -d'=' -f 2 for all kind of properties queried:



                            for example:



                            $ systemctl show -p ActiveState sshd | cut -d'=' -f2
                            active
                            $ systemctl show -p SubState sshd | cut -d'=' -f2
                            running





                            share|improve this answer



























                              2












                              2








                              2







                              Instead of using the sed command like in the answer of Oxmel, it is enough to use cut -d'=' -f 2 for all kind of properties queried:



                              for example:



                              $ systemctl show -p ActiveState sshd | cut -d'=' -f2
                              active
                              $ systemctl show -p SubState sshd | cut -d'=' -f2
                              running





                              share|improve this answer















                              Instead of using the sed command like in the answer of Oxmel, it is enough to use cut -d'=' -f 2 for all kind of properties queried:



                              for example:



                              $ systemctl show -p ActiveState sshd | cut -d'=' -f2
                              active
                              $ systemctl show -p SubState sshd | cut -d'=' -f2
                              running






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Aug 8 '18 at 13:18









                              Kevin Lemaire

                              1,181724




                              1,181724










                              answered Aug 8 '18 at 12:08









                              Mohamed ElMohamed El

                              1213




                              1213





















                                  1














                                  i find this useful for command line execution or if you are making scripts.



                                  Copied from @StephenKitt



                                  This will check if the service is down and perform service restart



                                  systemctl is-active --quiet <service name> || <service name> restart


                                  the || there checks if the return value from systemctl is non-zero meaning if it's not active as explained by the author.






                                  share|improve this answer



























                                    1














                                    i find this useful for command line execution or if you are making scripts.



                                    Copied from @StephenKitt



                                    This will check if the service is down and perform service restart



                                    systemctl is-active --quiet <service name> || <service name> restart


                                    the || there checks if the return value from systemctl is non-zero meaning if it's not active as explained by the author.






                                    share|improve this answer

























                                      1












                                      1








                                      1







                                      i find this useful for command line execution or if you are making scripts.



                                      Copied from @StephenKitt



                                      This will check if the service is down and perform service restart



                                      systemctl is-active --quiet <service name> || <service name> restart


                                      the || there checks if the return value from systemctl is non-zero meaning if it's not active as explained by the author.






                                      share|improve this answer













                                      i find this useful for command line execution or if you are making scripts.



                                      Copied from @StephenKitt



                                      This will check if the service is down and perform service restart



                                      systemctl is-active --quiet <service name> || <service name> restart


                                      the || there checks if the return value from systemctl is non-zero meaning if it's not active as explained by the author.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Feb 13 at 7:47









                                      asteriskasterisk

                                      111




                                      111





















                                          0
















                                          I am too late to the party , however using systemctl is-active along with && and || to this in script wont be the case all the time. The below is one I used for tomcat but can use it in method taking arguments and pass service name as arguments if u have to check multiple services but its out of scope here.



                                          STATUS=`systemctl is-active tomcat.service`
                                          if [[ $STATUS == 'active' ]]; then
                                          echo "Execute your tasks ....."
                                          else
                                          echo " Service not running.... so exiting "
                                          exit 1
                                          fi


                                          This is how I made use of.... Just sharing mine.



                                          and for the simplicity and easy stuffs, follow others explained here :



                                          systemctl -q is-active tomcat.service && echo "Tomcat Runnung" || echo "Service is not running at all "





                                          share|improve this answer



























                                            0
















                                            I am too late to the party , however using systemctl is-active along with && and || to this in script wont be the case all the time. The below is one I used for tomcat but can use it in method taking arguments and pass service name as arguments if u have to check multiple services but its out of scope here.



                                            STATUS=`systemctl is-active tomcat.service`
                                            if [[ $STATUS == 'active' ]]; then
                                            echo "Execute your tasks ....."
                                            else
                                            echo " Service not running.... so exiting "
                                            exit 1
                                            fi


                                            This is how I made use of.... Just sharing mine.



                                            and for the simplicity and easy stuffs, follow others explained here :



                                            systemctl -q is-active tomcat.service && echo "Tomcat Runnung" || echo "Service is not running at all "





                                            share|improve this answer

























                                              0












                                              0








                                              0









                                              I am too late to the party , however using systemctl is-active along with && and || to this in script wont be the case all the time. The below is one I used for tomcat but can use it in method taking arguments and pass service name as arguments if u have to check multiple services but its out of scope here.



                                              STATUS=`systemctl is-active tomcat.service`
                                              if [[ $STATUS == 'active' ]]; then
                                              echo "Execute your tasks ....."
                                              else
                                              echo " Service not running.... so exiting "
                                              exit 1
                                              fi


                                              This is how I made use of.... Just sharing mine.



                                              and for the simplicity and easy stuffs, follow others explained here :



                                              systemctl -q is-active tomcat.service && echo "Tomcat Runnung" || echo "Service is not running at all "





                                              share|improve this answer















                                              I am too late to the party , however using systemctl is-active along with && and || to this in script wont be the case all the time. The below is one I used for tomcat but can use it in method taking arguments and pass service name as arguments if u have to check multiple services but its out of scope here.



                                              STATUS=`systemctl is-active tomcat.service`
                                              if [[ $STATUS == 'active' ]]; then
                                              echo "Execute your tasks ....."
                                              else
                                              echo " Service not running.... so exiting "
                                              exit 1
                                              fi


                                              This is how I made use of.... Just sharing mine.



                                              and for the simplicity and easy stuffs, follow others explained here :



                                              systemctl -q is-active tomcat.service && echo "Tomcat Runnung" || echo "Service is not running at all "






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered yesterday









                                              SAGAR NairSAGAR Nair

                                              1011




                                              1011



























                                                  draft saved

                                                  draft discarded
















































                                                  Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid


                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f396630%2fthe-proper-way-to-test-if-a-service-is-running-in-a-script%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  -shell-script, systemd

                                                  Popular posts from this blog

                                                  Frič See also Navigation menuinternal link

                                                  Identify plant with long narrow paired leaves and reddish stems Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?What is this plant with long sharp leaves? Is it a weed?What is this 3ft high, stalky plant, with mid sized narrow leaves?What is this young shrub with opposite ovate, crenate leaves and reddish stems?What is this plant with large broad serrated leaves?Identify this upright branching weed with long leaves and reddish stemsPlease help me identify this bulbous plant with long, broad leaves and white flowersWhat is this small annual with narrow gray/green leaves and rust colored daisy-type flowers?What is this chilli plant?Does anyone know what type of chilli plant this is?Help identify this plant

                                                  fontconfig warning: “/etc/fonts/fonts.conf”, line 100: unknown “element blank” The 2019 Stack Overflow Developer Survey Results Are In“tar: unrecognized option --warning” during 'apt-get install'How to fix Fontconfig errorHow do I figure out which font file is chosen for a system generic font alias?Why are some apt-get-installed fonts being ignored by fc-list, xfontsel, etc?Reload settings in /etc/fonts/conf.dTaking 30 seconds longer to boot after upgrade from jessie to stretchHow to match multiple font names with a single <match> element?Adding a custom font to fontconfigRemoving fonts from fontconfig <match> resultsBroken fonts after upgrading Firefox ESR to latest Firefox