How to get the current Linux process ID from the command line a in shell-agnostic, language-agnostic way

Johnny Utahh picture Johnny Utahh · Nov 26, 2011 · Viewed 46.8k times · Source

How does one get their current process ID (pid) from the Linux command line in a shell-agnostic, language-agnostic way?

pidof(8) appears to have no option to get the calling process' pid. Bash, of course, has $$ - but for my generic usage, I can't rely on a shell (Bash or otherwise). And in some cases, I can't write a script or compilable program, so Bash / Python / C / C++ (etc.) will not work.

Here's a specific use case: I want to get the pid of the running, Python-Fabric-based, remote SSH process (where one may want to avoid assuming bash is running), so that among other things I can copy and/or create files and/or directories with unique filenames (as in mkdir /tmp/mydir.$$).

If we can solve the Fabric-specific problem, that's helpful - but it doesn't solve my long-term problem. For general-purpose usage in all future scenarios, I just want a command that returns what $$ delivers in Bash.

Answer

Aleksandr Levchuk picture Aleksandr Levchuk · Apr 22, 2013

From python:

$ python
>>> import os
>>> os.getpid()
12252