Extracting an Environment Variable From a Process

Occasionally I find it necessary to extract the value of an environment variable of a running process. For example to examine the TMUX value of a given process. I’ll use this later to determine if I should signal an emacs process when a TMUX session is reattached. This function depends on /proc/<pid>/environ being supported (apparently a linux thing). Here’s the function.

[Ed: updated version with suggested replacement from KnowsBash reddit-bash comment]

get-pid-env-var () {
    if [ -z "$1" -o -z "$2" ]; then
        echo "usage: get-pid-env-var pid var"
        return 1
    fi
    local key value
    while IFS='=' read -rd '' key value; do
        if [[ $key = "$2" ]]; then
            printf '%s\n' "$value"
            break
        fi
    done < "/proc/$1/environ"
}

And here it is in use.

[22:36:28 ~]$ ps x | grep emacs
24414 pts/1    S+     0:04 emacs -nw .bashrc
26751 pts/4    S+     0:00 grep emacs
[22:36:32 ~]$ get-pid-env-var 24414 TMUX
/tmp/tmux-21995/default,24155,0

Here’s the old version.

get-pid-env-var () {
    if [ -z "$1" -o -z "$2" ]; then
        echo "usage: get-pid-env-var pid var"
        return 1
    fi
    local VAR=$(tr "\0" "\n" < /proc/$1/environ | grep "$2=")
    if [ -z "$VAR" ]; then
        return 1
    fi
    echo ${VAR#$2=}
    return 0
}

Leave a Reply