You can't for sure. You have to make assumptions.
Pretend you're cron
and you're facing the worst case scenario for a second: there are multiple users logged in, and each user is running multiple X sessions. You'll have to guess the user (easy enough, we're executing their crontab) and one of that user's X sessions.
If we want to assume the user is running one and only one X session from a tty, and get that session's $DISPLAY
value we can use w
:
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
user tty1 16:32 7:15 0.21s 0.19s -zsh
user tty2 :1 15:52 48:13 2:17 0.08s /sbin/upstart
user pts/3 :1 16:19 0.00s 0.66s 0.00s w
For example here I'm logged in on tty1, on tty2 (where I'm running an X session) and on pts/3 (the terminal from which I'm running the command).
With a bit of parsing:
% w $(id -un) | awk 'NF > 7 && $2 ~ /tty[0-9]+/ {print $3; exit}'
:1
So, assuming all the above:
0 0 * * * DISPLAY=$(w $(id -un) | awk 'NF > 7 && $2 ~ /tty[0-9]+/ {print $3; exit}') command
Will make cron
execute command
with $DISPLAY
set to the first X session running in a tty's $DISPLAY
value found for the user.
:0
,:2
, and:5
(and often has more). So first you need to think about what you mean by "the X server" – steeldriver Mar 11 '16 at 15:28feh
on i3. – Ashhar Hasan Mar 11 '16 at 15:46