Skip to content

Instantly share code, notes, and snippets.

@naftulikay
Last active April 3, 2019 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naftulikay/f4c229b3c71fff9ac2102a0e03bd756f to your computer and use it in GitHub Desktop.
Save naftulikay/f4c229b3c71fff9ac2102a0e03bd756f to your computer and use it in GitHub Desktop.
Discover DBus Session and Display for a User

Discover a DBUS Session Deterministically

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
@NickSto
Copy link

NickSto commented Feb 2, 2019

Any reason for dot-naming the functions?

@cprn
Copy link

cprn commented Apr 3, 2019

Any reason for dot-naming the functions?

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").

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment