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 problemGet PID and return code from 1 line bash callWhy is “Doing an exit 130 is not the same as dying of SIGINT”?bash script: capturing tcp traffic on a remote server sometimes works, sometimes fails. No errorsWhat does typing a single exclamation mark do in Bash?Execute command and store everything to variable in bashWhy does bash 'read' exit with status 1?What does it mean when Duplicity exits with exit status 23?

Can you describe someone as luxurious? As in someone who likes luxurious things?

How do I prevent inappropriate ads from appearing in my game?

"Marked down as someone wanting to sell shares." What does that mean?

Why is participating in the European Parliamentary elections used as a threat?

If the Dominion rule using their Jem'Hadar troops, why is their life expectancy so low?

Hashing password to increase entropy

How do you say "Trust your struggle." in French?

What is the purpose of using a decision tree?

Trouble reading roman numeral notation with flats

Reason why a kingside attack is not justified

I keep switching characters, how do I stop?

Air travel with refrigerated insulin

Calculate Pi using Monte Carlo

Travelling in US for more than 90 days

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

What is the tangent at a sharp point on a curve?

Why would five hundred and five same as one?

Writing in a Christian voice

What is this high flying aircraft over Pennsylvania?

Make a Bowl of Alphabet Soup

Is this saw blade faulty?

Checking @@ROWCOUNT failing

What (if any) is the reason to buy in small local stores?

How to preserve electronics (computers, ipads, phones) for hundreds of years?



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 problemGet PID and return code from 1 line bash callWhy is “Doing an exit 130 is not the same as dying of SIGINT”?bash script: capturing tcp traffic on a remote server sometimes works, sometimes fails. No errorsWhat does typing a single exclamation mark do in Bash?Execute command and store everything to variable in bashWhy does bash 'read' exit with status 1?What does it mean when Duplicity exits with exit status 23?










2















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.




















  • 0 or 1 is exit status, but $(...) captures output.

    – Charles Duffy
    6 hours ago















2















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.




















  • 0 or 1 is exit status, but $(...) captures output.

    – Charles Duffy
    6 hours ago













2












2








2








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 6 hours 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 8 hours ago









TubeTube

111




111




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.












  • 0 or 1 is exit status, but $(...) captures output.

    – Charles Duffy
    6 hours ago

















  • 0 or 1 is exit status, but $(...) captures output.

    – Charles Duffy
    6 hours ago
















0 or 1 is exit status, but $(...) captures output.

– Charles Duffy
6 hours ago





0 or 1 is exit status, but $(...) captures output.

– Charles Duffy
6 hours ago










2 Answers
2






active

oldest

votes


















4














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
































    3














    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























    • if pgrep compton >/dev/null; then is the better practice, so one doesn't directly inspect $? at all. In addition to avoiding bugs where $? refers to a different command than you think it does when editing code to add logging or such, this also means that set -e will no longer treat pgrep returning 1 as cause to exit the script (because branching on its exit status marks it as "checked").

      – Charles Duffy
      6 hours ago











    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









    4














    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





























      4














      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



























        4












        4








        4







        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 6 hours ago

























        answered 7 hours ago









        KusalanandaKusalananda

        136k17257426




        136k17257426























            3














            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























            • if pgrep compton >/dev/null; then is the better practice, so one doesn't directly inspect $? at all. In addition to avoiding bugs where $? refers to a different command than you think it does when editing code to add logging or such, this also means that set -e will no longer treat pgrep returning 1 as cause to exit the script (because branching on its exit status marks it as "checked").

              – Charles Duffy
              6 hours ago
















            3














            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























            • if pgrep compton >/dev/null; then is the better practice, so one doesn't directly inspect $? at all. In addition to avoiding bugs where $? refers to a different command than you think it does when editing code to add logging or such, this also means that set -e will no longer treat pgrep returning 1 as cause to exit the script (because branching on its exit status marks it as "checked").

              – Charles Duffy
              6 hours ago














            3












            3








            3







            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 8 hours ago









            Jakub JindraJakub Jindra

            317310




            317310












            • if pgrep compton >/dev/null; then is the better practice, so one doesn't directly inspect $? at all. In addition to avoiding bugs where $? refers to a different command than you think it does when editing code to add logging or such, this also means that set -e will no longer treat pgrep returning 1 as cause to exit the script (because branching on its exit status marks it as "checked").

              – Charles Duffy
              6 hours ago


















            • if pgrep compton >/dev/null; then is the better practice, so one doesn't directly inspect $? at all. In addition to avoiding bugs where $? refers to a different command than you think it does when editing code to add logging or such, this also means that set -e will no longer treat pgrep returning 1 as cause to exit the script (because branching on its exit status marks it as "checked").

              – Charles Duffy
              6 hours ago

















            if pgrep compton >/dev/null; then is the better practice, so one doesn't directly inspect $? at all. In addition to avoiding bugs where $? refers to a different command than you think it does when editing code to add logging or such, this also means that set -e will no longer treat pgrep returning 1 as cause to exit the script (because branching on its exit status marks it as "checked").

            – Charles Duffy
            6 hours ago






            if pgrep compton >/dev/null; then is the better practice, so one doesn't directly inspect $? at all. In addition to avoiding bugs where $? refers to a different command than you think it does when editing code to add logging or such, this also means that set -e will no longer treat pgrep returning 1 as cause to exit the script (because branching on its exit status marks it as "checked").

            – Charles Duffy
            6 hours ago











            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

            How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

            Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

            Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр