Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Find running X sessions

tl;dr

{ ps -eo pid,command | awk '/-session/ {print $1}' | while read thispid; do cat /proc/${thispid}/environ | tr '\0' '\n' | grep "DISPLAY" | sed -e "s/^/${thispid} $( stat -c '%U' /proc/${thispid}/comm ) $( basename $( readlink -f /proc/${thispid}/exe ) ) /;"; done; } 2>/dev/null | grep -iE "xfce|cinnamon"

Explanation

I was working on a shell script that affects the running desktop environments. In order to find the running processes, owners, executable, and display session, I whipped up this one-liner. Obviously here, I limit my searches to specific types of desktop environments. I was getting a dbus-daemon and at- spi2-registryd which I neither understand nor care about, so I added the regular expression search at the end. Feel free to modify for your own use. Example output:

$ { ps -eo pid,command | awk '/-session/ {print $1}' | while read thispid; do cat /proc/${thispid}/environ | tr '\0' '\n' | grep "DISPLAY" | sed -e "s/^/${thispid} $( stat -c '%U' /proc/${thispid}/comm ) $( basename $( readlink -f /proc/${thispid}/exe ) ) /;"; done; } 2>/dev/null | grep -iE "xfce|cinnamon"
1791 bgstack15-local xfce4-session DISPLAY=:0

Comments