When I switch to root (sudo su), I first have to run xauth list
as myself then xauth add <last entry from xauth list>
once I'm root. I found a great little tip to make this easier by running xauth add $(xauth -f ~<my username>/.Xauthority list|tail -1)
. This is nice, but I wanted to automate it.
So, I went into /root/.bashrc and added this:
xauth add $(xauth -f ~$SUDO_USER/.Xauthority list|tail -1)
Unfortunately, that gives the error error in locking authority file ~<my user>/.Xauthority
It works if I just replace $SUDO_USER with my username. Clearly $SUDO_USER is set correctly because it knows to look for the correct authority file. So, what's going on here?
~
expansion is done before variable interpolation. If you do a strace, you will see that the actual error is No such file or directory
openat(AT_FDCWD, "~<myuser>/.Xauthority-c", O_WRONLY|O_CREAT|O_EXCL, 0600) = -1 ENOENT (No such file or directory)
write(2, "xauth: error in locking authori"..., 62xauth: error in locking authority file ~<myuser>/.Xauthority
use /home/$SUDO_USER/.Xauthority
instead