Search code examples
bashpid

Get the PID of a process launched in the same command line


I want to launch in bash a hello.sh script that does many things (writing in a file, printing in the screen), but I want to get its PID dumping it in a file, but I want to do it in the same command line because I could have different processes with the same file (many hello.sh launched).

So, I would like something like (pseudo-code): sh hello.sh > get_pid > pid_to_log. Thx.


Solution

  • You can do this

    ./myscript.sh & echo $! >> log.pid
    

    Then you will store your PID in a file. But perhaps you need to store also the date and hour.

    ./sleep.sh & echo $! `date` >> log.pid
    

    Example

    $ more sleep.sh
    sleep 10
    $ ./sleep.sh & echo $! `date` >> log.pid
    [1] 9588
    $ ./sleep.sh & echo $! `date` >> log.pid
    [2] 9640
    $ ./sleep.sh & echo $! `date` >> log.pid
    [3] 9646
    $ cat log.pid
    9588 Wed Jul 8 14:03:19 CEST 2020
    9640 Wed Jul 8 14:03:22 CEST 2020
    9646 Wed Jul 8 14:03:23 CEST 2020