How to get the command line for any process in Linux

“/proc” file system

Every process has an associated sub-directory entry under “/proc” in the form “/proc/<PID>“, where <PID> is the process identifier.  The “ps” command can be used to obtain the process identifier for any process by executing:

# ps aux | grep -i process_name | grep -v grep

For example:

peniwize@host:~$ ps aux | grep -i bash | grep -v grep
peniwize 2255 0.0 0.1 7044 3596 pts/1 Ss 18:52 0:00 bash
peniwize 2347 0.9 0.1 7044 3704 pts/2 Ss 19:08 0:00 bash

The second column is the process identifier (PID).


“/proc/<PID>/cmdline” file

Each process sub-directory also has a read-only “cmdline” file that contains the complete command line used to execute the process. The command line arguments are separated by by nulls instead of white space, and the ‘cmdline’ files does not end with a new-line, so it is necessary to replace all nulls with spaces (or tab, or whatever you want) in order to display them. This can be done with a simple sed filter. Here are examples of the command line both raw and processed by sed:

peniwize@host:~$ cat /proc/self/cmdline && printf "\n"
peniwize@host:~$ cat /proc/self/cmdline | sed 's/\x0/ /' && printf "\n"
cat /proc/self/cmdline

Notice that there is no space (fourth character) between “cat” and “/proc…” in the output of the first command but there is in the output of the second. Note that most modern Linux kernels are configured to create a directory named “self” in the “/proc” file-system. “self” is an alias for the PID of the currently running process, i.e. a process can easily access “/proc/<PID>/…” by accessing “proc/self/…”.

Simple bash script to display the command line for any process by PID or by name

# Argument 1 ($1) is the PID (or name) of the process whose command line should be shown.
if [[ "$1" =~ ^[0-9]+$ ]]; then
    PID="$(pidof $1)"
if [[ -z "$PID" ]]; then
    printf "Unable to resolve process: '$1'!\n"
    exit 1
cat /proc/$PID/cmdline | sed 's/\x0/ /' && printf "\n"

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: