Search code examples
bashmacosterminalpidio-redirection

Print PID to file


I'm trying to make a bash script to be run in a terminal that prints its own PID to a .txt file at the beginning of the script.

I know that you get the PID of a responsive terminal by typing in $$, but if I do it, the PID gets automatically executed and therefore the output is not the PID, but bash:PIDNUMVALUE: command not found, and if I print the output of $$ into a .txt file, the output will not be the PID, but bash:PIDNUMVALUE: command not found while I only want the PID to be printed in the txt file.

How do I do it?


Solution

  • Try this:

    echo $$ > my.pid
    

    Or use $BASHPID instead for better script readability IMO, but keep in mind some subtle differences between the two:

    Expands to the process ID of the current Bash process. This differs from $$ under certain circumstances, such as subshells that do not require Bash to be re-initialized.

    Check the Bash manual for further information.