Why can't I get pgrep output right to variable on bash script?2019 Community Moderator ElectionBash script doesn't TEE output to subdirectoryExiting a Bash script when a sudo child quitsConditional execution block with || and parentheses problemProcess being stopped randomlyHow to write bash script while using command as condition in if statement?Using spd-say in a bash script functionGet PID and return code from 1 line bash callbash script: capturing tcp traffic on a remote server sometimes works, sometimes fails. No errorsWhy does bash 'read' exit with status 1?Passing variable to “authorization: bearer” header with Curl and Bash

Taking the numerator and the denominator

Reason why a kingside attack is not justified

Why is indicated airspeed rather than ground speed used during the takeoff roll?

What is it called when someone votes for an option that's not their first choice?

Comic-book: Kids find a dead female superhero in the woods

Is divisi notation needed for brass or woodwind in an orchestra?

Strange behavior in TikZ draw command

Extract substring according to regexp with sed or grep

Would Poker (with *Zero* real-world currency involved) in an M-Rated (18+) Online game be constituted Online Gambling?

What is the period/term used describe Giuseppe Arcimboldo's style of painting?

What do the positive and negative (+/-) transmit and receive pins mean on Ethernet cables?

Asserting that Atheism and Theism are both faith based positions

Why would five hundred and five same as one?

Derivative of an interpolated function

When is the exact date for EOL of Ubuntu 14.04 LTS?

New Order #2: Turn My Way

Calculate Pi using Monte Carlo

Could a welfare state co-exist with mega corporations?

How do I lift the insulation blower into the attic?

Offset in split text content

Checking @@ROWCOUNT failing

Why didn’t Eve recognize the little cockroach as a living organism?

What 1968 Moog synthesizer was used in the Movie Apollo 11?

Pre-Employment Background Check With Consent For Future Checks



Why can't I get pgrep output right to variable on bash script?



2019 Community Moderator ElectionBash script doesn't TEE output to subdirectoryExiting a Bash script when a sudo child quitsConditional execution block with || and parentheses problemProcess being stopped randomlyHow to write bash script while using command as condition in if statement?Using spd-say in a bash script functionGet PID and return code from 1 line bash callbash script: capturing tcp traffic on a remote server sometimes works, sometimes fails. No errorsWhy does bash 'read' exit with status 1?Passing variable to “authorization: bearer” header with Curl and Bash










1















I'm trying to make a script to either quit compton if it's running or start it if it's not running. I've read from man that it should exit 1 if process is found, so I've tried to make a script that uses that... However this just doesn't work, It starts if it's closed but doesn't close it. what am I doing wrong ??



#!/bin/bash


status=$(pgrep compton 2>&1)

if [[ $status == 1 ]];
then
killall compton
else
exec compton -b
fi

echo $status









share|improve this question









New contributor




Tube is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    1















    I'm trying to make a script to either quit compton if it's running or start it if it's not running. I've read from man that it should exit 1 if process is found, so I've tried to make a script that uses that... However this just doesn't work, It starts if it's closed but doesn't close it. what am I doing wrong ??



    #!/bin/bash


    status=$(pgrep compton 2>&1)

    if [[ $status == 1 ]];
    then
    killall compton
    else
    exec compton -b
    fi

    echo $status









    share|improve this question









    New contributor




    Tube is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      1












      1








      1








      I'm trying to make a script to either quit compton if it's running or start it if it's not running. I've read from man that it should exit 1 if process is found, so I've tried to make a script that uses that... However this just doesn't work, It starts if it's closed but doesn't close it. what am I doing wrong ??



      #!/bin/bash


      status=$(pgrep compton 2>&1)

      if [[ $status == 1 ]];
      then
      killall compton
      else
      exec compton -b
      fi

      echo $status









      share|improve this question









      New contributor




      Tube is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.












      I'm trying to make a script to either quit compton if it's running or start it if it's not running. I've read from man that it should exit 1 if process is found, so I've tried to make a script that uses that... However this just doesn't work, It starts if it's closed but doesn't close it. what am I doing wrong ??



      #!/bin/bash


      status=$(pgrep compton 2>&1)

      if [[ $status == 1 ]];
      then
      killall compton
      else
      exec compton -b
      fi

      echo $status






      bash stdout stderr exit-status pgrep






      share|improve this question









      New contributor




      Tube is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Tube is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 5 mins ago









      Kusalananda

      136k17257426




      136k17257426






      New contributor




      Tube is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 2 hours ago









      TubeTube

      61




      61




      New contributor




      Tube is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Tube is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Tube is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          2 Answers
          2






          active

          oldest

          votes


















          2














          You should control exit status of pgrep process which will be in $? variable. Or check if $status variable where you're storing the output of pgrep is f.e. non zero-length string. The script in the question checks whether string in variable status is "1"



          so



          #!/bin/bash
          pgrep compton >/dev/null

          if [[ $? -eq 0 ]]
          then
          killall compton
          else
          exec compton -b
          fi


          or



          #!/bin/bash
          status=$(pgrep compton 2>&1)

          if [[ -n "$status" ]]
          then
          killall compton
          else
          exec compton -b
          fi





          share|improve this answer






























            2














            You are getting the pgrep output in your status variable. It's just not the output that you expect it to be.



            pgrep outputs the process IDs (PIDs) of the processes matching the pattern that you give it. If there is a process whose name matches compton, then $status would be the PID of that process, or of those processes. pgrep also returns an exit status, but an exit status is not captured by a command substitution as a string.



            In your test, you compare $status against 1. It is unlikely that compton has PID 1.




            If you want to kill any compton process if they exist, and start compton -b if no compton process exists, you may do that with



            #!/bin/sh

            if ! pkill compton; then
            exec compton -b
            fi


            This uses the exit status of pkill. The pkill tool works in an equivalent way to pgrep (they are usually distributed and installed as a pair) but instead of outputting PIDs of matching processes like pgrep would do, pkill sends the TERM signal (by default) to the matching processes.



            The if keyword uses the exit status of the command that you use with it.



            The ! inverts the sense of the test so that



            • If pkill compton succeeds, it means that there was one or several compton processes that have now been killed, or at least signalled, and exec compton -b will not be executed.


            • If pkill compton fails (no process matched the name, or there was some internal error in pkill), the body of the if statement would call your exec compton -b, which would replace the shell process with that of compton -b.






            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
              );



              );






              Tube is a new contributor. Be nice, and check out our Code of Conduct.









              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f507290%2fwhy-cant-i-get-pgrep-output-right-to-variable-on-bash-script%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              You should control exit status of pgrep process which will be in $? variable. Or check if $status variable where you're storing the output of pgrep is f.e. non zero-length string. The script in the question checks whether string in variable status is "1"



              so



              #!/bin/bash
              pgrep compton >/dev/null

              if [[ $? -eq 0 ]]
              then
              killall compton
              else
              exec compton -b
              fi


              or



              #!/bin/bash
              status=$(pgrep compton 2>&1)

              if [[ -n "$status" ]]
              then
              killall compton
              else
              exec compton -b
              fi





              share|improve this answer



























                2














                You should control exit status of pgrep process which will be in $? variable. Or check if $status variable where you're storing the output of pgrep is f.e. non zero-length string. The script in the question checks whether string in variable status is "1"



                so



                #!/bin/bash
                pgrep compton >/dev/null

                if [[ $? -eq 0 ]]
                then
                killall compton
                else
                exec compton -b
                fi


                or



                #!/bin/bash
                status=$(pgrep compton 2>&1)

                if [[ -n "$status" ]]
                then
                killall compton
                else
                exec compton -b
                fi





                share|improve this answer

























                  2












                  2








                  2







                  You should control exit status of pgrep process which will be in $? variable. Or check if $status variable where you're storing the output of pgrep is f.e. non zero-length string. The script in the question checks whether string in variable status is "1"



                  so



                  #!/bin/bash
                  pgrep compton >/dev/null

                  if [[ $? -eq 0 ]]
                  then
                  killall compton
                  else
                  exec compton -b
                  fi


                  or



                  #!/bin/bash
                  status=$(pgrep compton 2>&1)

                  if [[ -n "$status" ]]
                  then
                  killall compton
                  else
                  exec compton -b
                  fi





                  share|improve this answer













                  You should control exit status of pgrep process which will be in $? variable. Or check if $status variable where you're storing the output of pgrep is f.e. non zero-length string. The script in the question checks whether string in variable status is "1"



                  so



                  #!/bin/bash
                  pgrep compton >/dev/null

                  if [[ $? -eq 0 ]]
                  then
                  killall compton
                  else
                  exec compton -b
                  fi


                  or



                  #!/bin/bash
                  status=$(pgrep compton 2>&1)

                  if [[ -n "$status" ]]
                  then
                  killall compton
                  else
                  exec compton -b
                  fi






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 2 hours ago









                  Jakub JindraJakub Jindra

                  307310




                  307310























                      2














                      You are getting the pgrep output in your status variable. It's just not the output that you expect it to be.



                      pgrep outputs the process IDs (PIDs) of the processes matching the pattern that you give it. If there is a process whose name matches compton, then $status would be the PID of that process, or of those processes. pgrep also returns an exit status, but an exit status is not captured by a command substitution as a string.



                      In your test, you compare $status against 1. It is unlikely that compton has PID 1.




                      If you want to kill any compton process if they exist, and start compton -b if no compton process exists, you may do that with



                      #!/bin/sh

                      if ! pkill compton; then
                      exec compton -b
                      fi


                      This uses the exit status of pkill. The pkill tool works in an equivalent way to pgrep (they are usually distributed and installed as a pair) but instead of outputting PIDs of matching processes like pgrep would do, pkill sends the TERM signal (by default) to the matching processes.



                      The if keyword uses the exit status of the command that you use with it.



                      The ! inverts the sense of the test so that



                      • If pkill compton succeeds, it means that there was one or several compton processes that have now been killed, or at least signalled, and exec compton -b will not be executed.


                      • If pkill compton fails (no process matched the name, or there was some internal error in pkill), the body of the if statement would call your exec compton -b, which would replace the shell process with that of compton -b.






                      share|improve this answer





























                        2














                        You are getting the pgrep output in your status variable. It's just not the output that you expect it to be.



                        pgrep outputs the process IDs (PIDs) of the processes matching the pattern that you give it. If there is a process whose name matches compton, then $status would be the PID of that process, or of those processes. pgrep also returns an exit status, but an exit status is not captured by a command substitution as a string.



                        In your test, you compare $status against 1. It is unlikely that compton has PID 1.




                        If you want to kill any compton process if they exist, and start compton -b if no compton process exists, you may do that with



                        #!/bin/sh

                        if ! pkill compton; then
                        exec compton -b
                        fi


                        This uses the exit status of pkill. The pkill tool works in an equivalent way to pgrep (they are usually distributed and installed as a pair) but instead of outputting PIDs of matching processes like pgrep would do, pkill sends the TERM signal (by default) to the matching processes.



                        The if keyword uses the exit status of the command that you use with it.



                        The ! inverts the sense of the test so that



                        • If pkill compton succeeds, it means that there was one or several compton processes that have now been killed, or at least signalled, and exec compton -b will not be executed.


                        • If pkill compton fails (no process matched the name, or there was some internal error in pkill), the body of the if statement would call your exec compton -b, which would replace the shell process with that of compton -b.






                        share|improve this answer



























                          2












                          2








                          2







                          You are getting the pgrep output in your status variable. It's just not the output that you expect it to be.



                          pgrep outputs the process IDs (PIDs) of the processes matching the pattern that you give it. If there is a process whose name matches compton, then $status would be the PID of that process, or of those processes. pgrep also returns an exit status, but an exit status is not captured by a command substitution as a string.



                          In your test, you compare $status against 1. It is unlikely that compton has PID 1.




                          If you want to kill any compton process if they exist, and start compton -b if no compton process exists, you may do that with



                          #!/bin/sh

                          if ! pkill compton; then
                          exec compton -b
                          fi


                          This uses the exit status of pkill. The pkill tool works in an equivalent way to pgrep (they are usually distributed and installed as a pair) but instead of outputting PIDs of matching processes like pgrep would do, pkill sends the TERM signal (by default) to the matching processes.



                          The if keyword uses the exit status of the command that you use with it.



                          The ! inverts the sense of the test so that



                          • If pkill compton succeeds, it means that there was one or several compton processes that have now been killed, or at least signalled, and exec compton -b will not be executed.


                          • If pkill compton fails (no process matched the name, or there was some internal error in pkill), the body of the if statement would call your exec compton -b, which would replace the shell process with that of compton -b.






                          share|improve this answer















                          You are getting the pgrep output in your status variable. It's just not the output that you expect it to be.



                          pgrep outputs the process IDs (PIDs) of the processes matching the pattern that you give it. If there is a process whose name matches compton, then $status would be the PID of that process, or of those processes. pgrep also returns an exit status, but an exit status is not captured by a command substitution as a string.



                          In your test, you compare $status against 1. It is unlikely that compton has PID 1.




                          If you want to kill any compton process if they exist, and start compton -b if no compton process exists, you may do that with



                          #!/bin/sh

                          if ! pkill compton; then
                          exec compton -b
                          fi


                          This uses the exit status of pkill. The pkill tool works in an equivalent way to pgrep (they are usually distributed and installed as a pair) but instead of outputting PIDs of matching processes like pgrep would do, pkill sends the TERM signal (by default) to the matching processes.



                          The if keyword uses the exit status of the command that you use with it.



                          The ! inverts the sense of the test so that



                          • If pkill compton succeeds, it means that there was one or several compton processes that have now been killed, or at least signalled, and exec compton -b will not be executed.


                          • If pkill compton fails (no process matched the name, or there was some internal error in pkill), the body of the if statement would call your exec compton -b, which would replace the shell process with that of compton -b.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 13 mins ago

























                          answered 1 hour ago









                          KusalanandaKusalananda

                          136k17257426




                          136k17257426




















                              Tube is a new contributor. Be nice, and check out our Code of Conduct.









                              draft saved

                              draft discarded


















                              Tube is a new contributor. Be nice, and check out our Code of Conduct.












                              Tube is a new contributor. Be nice, and check out our Code of Conduct.











                              Tube is a new contributor. Be nice, and check out our Code of Conduct.














                              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%2f507290%2fwhy-cant-i-get-pgrep-output-right-to-variable-on-bash-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







                              Popular posts from this blog

                              Are there any AGPL-style licences that require source code modifications to be public? Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Force derivative works to be publicAre there any GPL like licenses for Apple App Store?Do you violate the GPL if you provide source code that cannot be compiled?GPL - is it distribution to use libraries in an appliance loaned to customers?Distributing App for free which uses GPL'ed codeModifications of server software under GPL, with web/CLI interfaceDoes using an AGPLv3-licensed library prevent me from dual-licensing my own source code?Can I publish only select code under GPLv3 from a private project?Is there published precedent regarding the scope of covered work that uses AGPL software?If MIT licensed code links to GPL licensed code what should be the license of the resulting binary program?If I use a public API endpoint that has its source code licensed under AGPL in my app, do I need to disclose my source?

                              2013 GY136 Descoberta | Órbita | Referências Menu de navegação«List Of Centaurs and Scattered-Disk Objects»«List of Known Trans-Neptunian Objects»

                              Button changing it's text & action. Good or terrible? The 2019 Stack Overflow Developer Survey Results Are Inchanging text on user mouseoverShould certain functions be “hard to find” for powerusers to discover?Custom liking function - do I need user login?Using different checkbox style for different checkbox behaviorBest Practices: Save and Exit in Software UIInteraction with remote validated formMore efficient UI to progress the user through a complicated process?Designing a popup notice for a gameShould bulk-editing functions be hidden until a table row is selected, or is there a better solution?Is it bad practice to disable (replace) the context menu?