Skip to content

Instantly share code, notes, and snippets.

@jackpot51
Created July 14, 2017 15:46
Show Gist options
  • Save jackpot51/c645400ef747b3f4d3367af20120f59a to your computer and use it in GitHub Desktop.
Save jackpot51/c645400ef747b3f4d3367af20120f59a to your computer and use it in GitHub Desktop.
#!/bin/bash -e
# Run a command as the foreground user, with their DISPLAY
if [ "$EUID" -ne "0" ]
then
echo "not running as root"
exit 1
fi
if [ "$#" -eq 0 ]
then
echo "no command provided"
exit 1
fi
USER="$(who | awk -v vt=tty$(fgconsole) '$0 ~ vt {print $1}')"
if [ -z "$USER" ]
then
echo "logged in user not found"
exit 1
fi
DISPLAY="$(who | awk -v vt=tty$(fgconsole) '$0 ~ vt {print $5}' | sed 's/^(\|)$//g')"
if [ -z "$DISPLAY" ]
then
echo "logged in display not found"
exit 1
fi
sudo -u "$USER" DISPLAY="$DISPLAY" -- "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment