How to get the pid of the last executed command in shell script?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
207
down vote

favorite
27












I want to have a shell script like this:



my-app &
echo $my-app-pid


But I do not know how the get the pid of the just executed command.



I know I can just use the jobs -p my-app command to grep the pid. But if I want to execute the shell multiple times, this method will not work. Because the jobspec is ambiguous.










share|improve this question



























    up vote
    207
    down vote

    favorite
    27












    I want to have a shell script like this:



    my-app &
    echo $my-app-pid


    But I do not know how the get the pid of the just executed command.



    I know I can just use the jobs -p my-app command to grep the pid. But if I want to execute the shell multiple times, this method will not work. Because the jobspec is ambiguous.










    share|improve this question

























      up vote
      207
      down vote

      favorite
      27









      up vote
      207
      down vote

      favorite
      27






      27





      I want to have a shell script like this:



      my-app &
      echo $my-app-pid


      But I do not know how the get the pid of the just executed command.



      I know I can just use the jobs -p my-app command to grep the pid. But if I want to execute the shell multiple times, this method will not work. Because the jobspec is ambiguous.










      share|improve this question















      I want to have a shell script like this:



      my-app &
      echo $my-app-pid


      But I do not know how the get the pid of the just executed command.



      I know I can just use the jobs -p my-app command to grep the pid. But if I want to execute the shell multiple times, this method will not work. Because the jobspec is ambiguous.







      bash shell process background-process






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 25 '16 at 11:11









      Jeff Schaller

      34.9k952115




      34.9k952115










      asked Jan 30 '12 at 11:34









      davidshen84

      2,03732233




      2,03732233




















          4 Answers
          4






          active

          oldest

          votes

















          up vote
          288
          down vote



          accepted










          The PID of the last executed command is in the $! shell variable:



          my-app &
          echo $!





          share|improve this answer


















          • 1




            It is printing pid as for eg. [1] 893 . I want only number.
            – user3153014
            Sep 4 '14 at 11:47







          • 29




            It should be noted that this stands for programs started in the background. If no background processes have been started the parameter is not set.
            – ramrunner
            Nov 17 '14 at 21:52






          • 5




            Another worthy solution is suggested in (a comment to an answer to) How to get pid of just started process: oh, and the "oneliner": /bin/sh -c 'echo $$>/tmp/my.pid && exec program args' & – sysfault Nov 24 '10 at 14:28
            – imz -- Ivan Zakharyaschev
            Jun 2 '15 at 14:11






          • 14




            @user3153014 String s like "[2] 2625" are printed by shell after starting background task. This is not related to output of echo $!
            – Petr Gladkikh
            Jul 26 '15 at 5:21


















          up vote
          53
          down vote













          Get PID:



          #!/bin/bash
          my-app &
          echo $!


          Save PID in variable:



          #!/bin/bash
          my-app &
          export APP_PID=$!


          Save all instances PID in text file:



          #!/bin/bash
          my-app &
          echo $! >>/tmp/my-app.pid


          Save output, errors and PID in separated files:



          #!/bin/bash
          my-app >/tmp/my-app.log 2>/tmp/my-app.error.log &
          echo $! >>/tmp/my-app.pid

          echo "my-app PID's: $(cat /tmp/my-app.pid)"





          share|improve this answer


















          • 2




            The question didn't ask about redirection, then your answer is the mostly the same as the accepted one except that if an instance of my-app finishes, and perhaps even worse its PID gets reused later, you'll have bad information in your file. I don't think this answer adds much of value to the existing accepted answer really
            – Eric Renouf
            Jan 22 '16 at 15:12










          • @EricRenouf post updated!
            – Eduardo Cuomo
            Jan 22 '16 at 15:42










          • another derivative that might be useful. This gets the PID and at the same time treats it as a (mostly) foreground process: sleep 4 | grep INVALID & export MY_PID=$!; fg; echo $MY_PID returned with $? `
            – mlathe
            Apr 26 at 21:53










          • isnt APP=main & a way to grab PID?
            – MrMesees
            Aug 30 at 7:54

















          up vote
          3
          down vote













          Try something like



          pidof my_app >> /tmp/my_app.pid





          share|improve this answer



























            up vote
            -4
            down vote













            Try something like this:



             ps ef | grep "[m]y-app" | awk 'print $2'


            Placing the first letter of your process between [ ] makes sure you do not get the grep process in your list. If needed you can also add a grep on your username.






            share|improve this answer


















            • 9




              That's very fragile at best and doesn't work if my-app is executed more than once - davidshen84 specifically worries about that cas.
              – Mat
              Jan 30 '12 at 12:10






            • 2




              If you even go this route, you should use pgrep instead.
              – Willem
              Jan 19 '15 at 12: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',
            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%2f30370%2fhow-to-get-the-pid-of-the-last-executed-command-in-shell-script%23new-answer', 'question_page');

            );

            Post as a guest






























            4 Answers
            4






            active

            oldest

            votes








            4 Answers
            4






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            288
            down vote



            accepted










            The PID of the last executed command is in the $! shell variable:



            my-app &
            echo $!





            share|improve this answer


















            • 1




              It is printing pid as for eg. [1] 893 . I want only number.
              – user3153014
              Sep 4 '14 at 11:47







            • 29




              It should be noted that this stands for programs started in the background. If no background processes have been started the parameter is not set.
              – ramrunner
              Nov 17 '14 at 21:52






            • 5




              Another worthy solution is suggested in (a comment to an answer to) How to get pid of just started process: oh, and the "oneliner": /bin/sh -c 'echo $$>/tmp/my.pid && exec program args' & – sysfault Nov 24 '10 at 14:28
              – imz -- Ivan Zakharyaschev
              Jun 2 '15 at 14:11






            • 14




              @user3153014 String s like "[2] 2625" are printed by shell after starting background task. This is not related to output of echo $!
              – Petr Gladkikh
              Jul 26 '15 at 5:21















            up vote
            288
            down vote



            accepted










            The PID of the last executed command is in the $! shell variable:



            my-app &
            echo $!





            share|improve this answer


















            • 1




              It is printing pid as for eg. [1] 893 . I want only number.
              – user3153014
              Sep 4 '14 at 11:47







            • 29




              It should be noted that this stands for programs started in the background. If no background processes have been started the parameter is not set.
              – ramrunner
              Nov 17 '14 at 21:52






            • 5




              Another worthy solution is suggested in (a comment to an answer to) How to get pid of just started process: oh, and the "oneliner": /bin/sh -c 'echo $$>/tmp/my.pid && exec program args' & – sysfault Nov 24 '10 at 14:28
              – imz -- Ivan Zakharyaschev
              Jun 2 '15 at 14:11






            • 14




              @user3153014 String s like "[2] 2625" are printed by shell after starting background task. This is not related to output of echo $!
              – Petr Gladkikh
              Jul 26 '15 at 5:21













            up vote
            288
            down vote



            accepted







            up vote
            288
            down vote



            accepted






            The PID of the last executed command is in the $! shell variable:



            my-app &
            echo $!





            share|improve this answer














            The PID of the last executed command is in the $! shell variable:



            my-app &
            echo $!






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 8 mins ago









            brandizzi

            1,30911423




            1,30911423










            answered Jan 30 '12 at 11:42









            enzotib

            32.9k710292




            32.9k710292







            • 1




              It is printing pid as for eg. [1] 893 . I want only number.
              – user3153014
              Sep 4 '14 at 11:47







            • 29




              It should be noted that this stands for programs started in the background. If no background processes have been started the parameter is not set.
              – ramrunner
              Nov 17 '14 at 21:52






            • 5




              Another worthy solution is suggested in (a comment to an answer to) How to get pid of just started process: oh, and the "oneliner": /bin/sh -c 'echo $$>/tmp/my.pid && exec program args' & – sysfault Nov 24 '10 at 14:28
              – imz -- Ivan Zakharyaschev
              Jun 2 '15 at 14:11






            • 14




              @user3153014 String s like "[2] 2625" are printed by shell after starting background task. This is not related to output of echo $!
              – Petr Gladkikh
              Jul 26 '15 at 5:21













            • 1




              It is printing pid as for eg. [1] 893 . I want only number.
              – user3153014
              Sep 4 '14 at 11:47







            • 29




              It should be noted that this stands for programs started in the background. If no background processes have been started the parameter is not set.
              – ramrunner
              Nov 17 '14 at 21:52






            • 5




              Another worthy solution is suggested in (a comment to an answer to) How to get pid of just started process: oh, and the "oneliner": /bin/sh -c 'echo $$>/tmp/my.pid && exec program args' & – sysfault Nov 24 '10 at 14:28
              – imz -- Ivan Zakharyaschev
              Jun 2 '15 at 14:11






            • 14




              @user3153014 String s like "[2] 2625" are printed by shell after starting background task. This is not related to output of echo $!
              – Petr Gladkikh
              Jul 26 '15 at 5:21








            1




            1




            It is printing pid as for eg. [1] 893 . I want only number.
            – user3153014
            Sep 4 '14 at 11:47





            It is printing pid as for eg. [1] 893 . I want only number.
            – user3153014
            Sep 4 '14 at 11:47





            29




            29




            It should be noted that this stands for programs started in the background. If no background processes have been started the parameter is not set.
            – ramrunner
            Nov 17 '14 at 21:52




            It should be noted that this stands for programs started in the background. If no background processes have been started the parameter is not set.
            – ramrunner
            Nov 17 '14 at 21:52




            5




            5




            Another worthy solution is suggested in (a comment to an answer to) How to get pid of just started process: oh, and the "oneliner": /bin/sh -c 'echo $$>/tmp/my.pid && exec program args' & – sysfault Nov 24 '10 at 14:28
            – imz -- Ivan Zakharyaschev
            Jun 2 '15 at 14:11




            Another worthy solution is suggested in (a comment to an answer to) How to get pid of just started process: oh, and the "oneliner": /bin/sh -c 'echo $$>/tmp/my.pid && exec program args' & – sysfault Nov 24 '10 at 14:28
            – imz -- Ivan Zakharyaschev
            Jun 2 '15 at 14:11




            14




            14




            @user3153014 String s like "[2] 2625" are printed by shell after starting background task. This is not related to output of echo $!
            – Petr Gladkikh
            Jul 26 '15 at 5:21





            @user3153014 String s like "[2] 2625" are printed by shell after starting background task. This is not related to output of echo $!
            – Petr Gladkikh
            Jul 26 '15 at 5:21













            up vote
            53
            down vote













            Get PID:



            #!/bin/bash
            my-app &
            echo $!


            Save PID in variable:



            #!/bin/bash
            my-app &
            export APP_PID=$!


            Save all instances PID in text file:



            #!/bin/bash
            my-app &
            echo $! >>/tmp/my-app.pid


            Save output, errors and PID in separated files:



            #!/bin/bash
            my-app >/tmp/my-app.log 2>/tmp/my-app.error.log &
            echo $! >>/tmp/my-app.pid

            echo "my-app PID's: $(cat /tmp/my-app.pid)"





            share|improve this answer


















            • 2




              The question didn't ask about redirection, then your answer is the mostly the same as the accepted one except that if an instance of my-app finishes, and perhaps even worse its PID gets reused later, you'll have bad information in your file. I don't think this answer adds much of value to the existing accepted answer really
              – Eric Renouf
              Jan 22 '16 at 15:12










            • @EricRenouf post updated!
              – Eduardo Cuomo
              Jan 22 '16 at 15:42










            • another derivative that might be useful. This gets the PID and at the same time treats it as a (mostly) foreground process: sleep 4 | grep INVALID & export MY_PID=$!; fg; echo $MY_PID returned with $? `
              – mlathe
              Apr 26 at 21:53










            • isnt APP=main & a way to grab PID?
              – MrMesees
              Aug 30 at 7:54














            up vote
            53
            down vote













            Get PID:



            #!/bin/bash
            my-app &
            echo $!


            Save PID in variable:



            #!/bin/bash
            my-app &
            export APP_PID=$!


            Save all instances PID in text file:



            #!/bin/bash
            my-app &
            echo $! >>/tmp/my-app.pid


            Save output, errors and PID in separated files:



            #!/bin/bash
            my-app >/tmp/my-app.log 2>/tmp/my-app.error.log &
            echo $! >>/tmp/my-app.pid

            echo "my-app PID's: $(cat /tmp/my-app.pid)"





            share|improve this answer


















            • 2




              The question didn't ask about redirection, then your answer is the mostly the same as the accepted one except that if an instance of my-app finishes, and perhaps even worse its PID gets reused later, you'll have bad information in your file. I don't think this answer adds much of value to the existing accepted answer really
              – Eric Renouf
              Jan 22 '16 at 15:12










            • @EricRenouf post updated!
              – Eduardo Cuomo
              Jan 22 '16 at 15:42










            • another derivative that might be useful. This gets the PID and at the same time treats it as a (mostly) foreground process: sleep 4 | grep INVALID & export MY_PID=$!; fg; echo $MY_PID returned with $? `
              – mlathe
              Apr 26 at 21:53










            • isnt APP=main & a way to grab PID?
              – MrMesees
              Aug 30 at 7:54












            up vote
            53
            down vote










            up vote
            53
            down vote









            Get PID:



            #!/bin/bash
            my-app &
            echo $!


            Save PID in variable:



            #!/bin/bash
            my-app &
            export APP_PID=$!


            Save all instances PID in text file:



            #!/bin/bash
            my-app &
            echo $! >>/tmp/my-app.pid


            Save output, errors and PID in separated files:



            #!/bin/bash
            my-app >/tmp/my-app.log 2>/tmp/my-app.error.log &
            echo $! >>/tmp/my-app.pid

            echo "my-app PID's: $(cat /tmp/my-app.pid)"





            share|improve this answer














            Get PID:



            #!/bin/bash
            my-app &
            echo $!


            Save PID in variable:



            #!/bin/bash
            my-app &
            export APP_PID=$!


            Save all instances PID in text file:



            #!/bin/bash
            my-app &
            echo $! >>/tmp/my-app.pid


            Save output, errors and PID in separated files:



            #!/bin/bash
            my-app >/tmp/my-app.log 2>/tmp/my-app.error.log &
            echo $! >>/tmp/my-app.pid

            echo "my-app PID's: $(cat /tmp/my-app.pid)"






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Aug 30 at 13:39

























            answered Jan 22 '16 at 15:04









            Eduardo Cuomo

            68856




            68856







            • 2




              The question didn't ask about redirection, then your answer is the mostly the same as the accepted one except that if an instance of my-app finishes, and perhaps even worse its PID gets reused later, you'll have bad information in your file. I don't think this answer adds much of value to the existing accepted answer really
              – Eric Renouf
              Jan 22 '16 at 15:12










            • @EricRenouf post updated!
              – Eduardo Cuomo
              Jan 22 '16 at 15:42










            • another derivative that might be useful. This gets the PID and at the same time treats it as a (mostly) foreground process: sleep 4 | grep INVALID & export MY_PID=$!; fg; echo $MY_PID returned with $? `
              – mlathe
              Apr 26 at 21:53










            • isnt APP=main & a way to grab PID?
              – MrMesees
              Aug 30 at 7:54












            • 2




              The question didn't ask about redirection, then your answer is the mostly the same as the accepted one except that if an instance of my-app finishes, and perhaps even worse its PID gets reused later, you'll have bad information in your file. I don't think this answer adds much of value to the existing accepted answer really
              – Eric Renouf
              Jan 22 '16 at 15:12










            • @EricRenouf post updated!
              – Eduardo Cuomo
              Jan 22 '16 at 15:42










            • another derivative that might be useful. This gets the PID and at the same time treats it as a (mostly) foreground process: sleep 4 | grep INVALID & export MY_PID=$!; fg; echo $MY_PID returned with $? `
              – mlathe
              Apr 26 at 21:53










            • isnt APP=main & a way to grab PID?
              – MrMesees
              Aug 30 at 7:54







            2




            2




            The question didn't ask about redirection, then your answer is the mostly the same as the accepted one except that if an instance of my-app finishes, and perhaps even worse its PID gets reused later, you'll have bad information in your file. I don't think this answer adds much of value to the existing accepted answer really
            – Eric Renouf
            Jan 22 '16 at 15:12




            The question didn't ask about redirection, then your answer is the mostly the same as the accepted one except that if an instance of my-app finishes, and perhaps even worse its PID gets reused later, you'll have bad information in your file. I don't think this answer adds much of value to the existing accepted answer really
            – Eric Renouf
            Jan 22 '16 at 15:12












            @EricRenouf post updated!
            – Eduardo Cuomo
            Jan 22 '16 at 15:42




            @EricRenouf post updated!
            – Eduardo Cuomo
            Jan 22 '16 at 15:42












            another derivative that might be useful. This gets the PID and at the same time treats it as a (mostly) foreground process: sleep 4 | grep INVALID & export MY_PID=$!; fg; echo $MY_PID returned with $? `
            – mlathe
            Apr 26 at 21:53




            another derivative that might be useful. This gets the PID and at the same time treats it as a (mostly) foreground process: sleep 4 | grep INVALID & export MY_PID=$!; fg; echo $MY_PID returned with $? `
            – mlathe
            Apr 26 at 21:53












            isnt APP=main & a way to grab PID?
            – MrMesees
            Aug 30 at 7:54




            isnt APP=main & a way to grab PID?
            – MrMesees
            Aug 30 at 7:54










            up vote
            3
            down vote













            Try something like



            pidof my_app >> /tmp/my_app.pid





            share|improve this answer
























              up vote
              3
              down vote













              Try something like



              pidof my_app >> /tmp/my_app.pid





              share|improve this answer






















                up vote
                3
                down vote










                up vote
                3
                down vote









                Try something like



                pidof my_app >> /tmp/my_app.pid





                share|improve this answer












                Try something like



                pidof my_app >> /tmp/my_app.pid






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 9 '16 at 16:24









                Piyush Jain

                30816




                30816




















                    up vote
                    -4
                    down vote













                    Try something like this:



                     ps ef | grep "[m]y-app" | awk 'print $2'


                    Placing the first letter of your process between [ ] makes sure you do not get the grep process in your list. If needed you can also add a grep on your username.






                    share|improve this answer


















                    • 9




                      That's very fragile at best and doesn't work if my-app is executed more than once - davidshen84 specifically worries about that cas.
                      – Mat
                      Jan 30 '12 at 12:10






                    • 2




                      If you even go this route, you should use pgrep instead.
                      – Willem
                      Jan 19 '15 at 12:41














                    up vote
                    -4
                    down vote













                    Try something like this:



                     ps ef | grep "[m]y-app" | awk 'print $2'


                    Placing the first letter of your process between [ ] makes sure you do not get the grep process in your list. If needed you can also add a grep on your username.






                    share|improve this answer


















                    • 9




                      That's very fragile at best and doesn't work if my-app is executed more than once - davidshen84 specifically worries about that cas.
                      – Mat
                      Jan 30 '12 at 12:10






                    • 2




                      If you even go this route, you should use pgrep instead.
                      – Willem
                      Jan 19 '15 at 12:41












                    up vote
                    -4
                    down vote










                    up vote
                    -4
                    down vote









                    Try something like this:



                     ps ef | grep "[m]y-app" | awk 'print $2'


                    Placing the first letter of your process between [ ] makes sure you do not get the grep process in your list. If needed you can also add a grep on your username.






                    share|improve this answer














                    Try something like this:



                     ps ef | grep "[m]y-app" | awk 'print $2'


                    Placing the first letter of your process between [ ] makes sure you do not get the grep process in your list. If needed you can also add a grep on your username.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 22 '16 at 15:08









                    Eduardo Cuomo

                    68856




                    68856










                    answered Jan 30 '12 at 11:42









                    Goez

                    1,14085




                    1,14085







                    • 9




                      That's very fragile at best and doesn't work if my-app is executed more than once - davidshen84 specifically worries about that cas.
                      – Mat
                      Jan 30 '12 at 12:10






                    • 2




                      If you even go this route, you should use pgrep instead.
                      – Willem
                      Jan 19 '15 at 12:41












                    • 9




                      That's very fragile at best and doesn't work if my-app is executed more than once - davidshen84 specifically worries about that cas.
                      – Mat
                      Jan 30 '12 at 12:10






                    • 2




                      If you even go this route, you should use pgrep instead.
                      – Willem
                      Jan 19 '15 at 12:41







                    9




                    9




                    That's very fragile at best and doesn't work if my-app is executed more than once - davidshen84 specifically worries about that cas.
                    – Mat
                    Jan 30 '12 at 12:10




                    That's very fragile at best and doesn't work if my-app is executed more than once - davidshen84 specifically worries about that cas.
                    – Mat
                    Jan 30 '12 at 12:10




                    2




                    2




                    If you even go this route, you should use pgrep instead.
                    – Willem
                    Jan 19 '15 at 12:41




                    If you even go this route, you should use pgrep instead.
                    – Willem
                    Jan 19 '15 at 12:41

















                     

                    draft saved


                    draft discarded















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f30370%2fhow-to-get-the-pid-of-the-last-executed-command-in-shell-script%23new-answer', 'question_page');

                    );

                    Post as a guest













































































                    Popular posts from this blog

                    Peggy Mitchell

                    Palaiologos

                    The Forum (Inglewood, California)