A set of Bash functions and a main method:
#!/usr/bin/env bash
function .dbus-session-pid() {
# get all procs by this user which are running dbus-daemon that have --session in the flags
ps aux | awk -v u=$USER -v b=/usr/bin/dbus-daemon '$1 == u && $11 == b {print $0;}' | \
grep -P '\s+--session\b' | awk '{print $2;}'
}
function .dbus-pid-to-display() {
local dbus_session_pid=$1
grep -z DISPLAY /proc/$dbus_session_pid/environ | awk -F = '{print $2;}'
}
function main() {
local args=("$@")
local dbus_pid="$(.dbus-session-pid)"
local display="$(.dbus-pid-to-display $dbus_pid)"
echo "$USER: DBus Session Process Id $dbus_pid, DISPLAY=$display"
}
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
set -e
main "$@"
fi
An example invocation yields the following for me:
naftuli: DBus Session Process Id 2230, DISPLAY=:0
When you normally source a script file in shell, all functions declared in global scope get declared and become available to call in that shell session (as commands). In some shells (can't remember how
bash
acts by default) prefixing function with a dot prevents that behavior (I heard people calling those "hidden functions").