Why can't I get pgrep output right to variable on bash script?Bash 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?

India just shot down a satellite from the ground. At what altitude range is the resulting debris field?

Sort a list by elements of another list

Unreliable Magic - Is it worth it?

Shortcut for value of this indefinite integral?

Is `x >> pure y` equivalent to `liftM (const y) x`

What is the opposite of 'gravitas'?

Purchasing a ticket for someone else in another country?

Is expanding the research of a group into machine learning as a PhD student risky?

How do scammers retract money, while you can’t?

What does 算不上 mean in 算不上太美好的日子?

How to Reset Passwords on Multiple Websites Easily?

Sequence of Tenses: Translating the subjunctive

Term for the "extreme-extension" version of a straw man fallacy?

Is this apparent Class Action settlement a spam message?

I'm in charge of equipment buying but no one's ever happy with what I choose. How to fix this?

How do I rename a Linux host without needing to reboot for the rename to take effect?

What is the difference between "behavior" and "behaviour"?

Increase performance creating Mandelbrot set in python

Why didn't Theresa May consult with Parliament before negotiating a deal with the EU?

Avoiding estate tax by giving multiple gifts

Opposite of a diet

What can we do to stop prior company from asking us questions?

Why escape if the_content isnt?

Roman Numeral Treatment of Suspensions



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


Bash 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?













3















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



















  • 1





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

    – Charles Duffy
    Mar 19 at 23:41











  • grab $? . do man bash.

    – user2497
    Mar 20 at 19:09















3















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



















  • 1





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

    – Charles Duffy
    Mar 19 at 23:41











  • grab $? . do man bash.

    – user2497
    Mar 20 at 19:09













3












3








3








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
















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















share|improve this question













share|improve this question




share|improve this question








edited Mar 19 at 23:19









Kusalananda

138k17258426




138k17258426










asked Mar 19 at 21:04









TubeTube

161




161







  • 1





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

    – Charles Duffy
    Mar 19 at 23:41











  • grab $? . do man bash.

    – user2497
    Mar 20 at 19:09












  • 1





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

    – Charles Duffy
    Mar 19 at 23:41











  • grab $? . do man bash.

    – user2497
    Mar 20 at 19:09







1




1





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

– Charles Duffy
Mar 19 at 23:41





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

– Charles Duffy
Mar 19 at 23:41













grab $? . do man bash.

– user2497
Mar 20 at 19:09





grab $? . do man bash.

– user2497
Mar 20 at 19:09










2 Answers
2






active

oldest

votes


















8














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 the process resulting from running compton -b.






share|improve this answer
































    5














    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


















    • 3





      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
      Mar 19 at 23:41











    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%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









    8














    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 the process resulting from running compton -b.






    share|improve this answer





























      8














      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 the process resulting from running compton -b.






      share|improve this answer



























        8












        8








        8







        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 the process resulting from running 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 the process resulting from running compton -b.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited yesterday

























        answered Mar 19 at 22:00









        KusalanandaKusalananda

        138k17258426




        138k17258426























            5














            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


















            • 3





              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
              Mar 19 at 23:41
















            5














            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


















            • 3





              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
              Mar 19 at 23:41














            5












            5








            5







            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 Mar 19 at 21:23









            Jakub JindraJakub Jindra

            399310




            399310







            • 3





              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
              Mar 19 at 23:41













            • 3





              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
              Mar 19 at 23:41








            3




            3





            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
            Mar 19 at 23:41






            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
            Mar 19 at 23:41


















            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%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







            -bash, exit-status, pgrep, stderr, stdout

            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