setting gsettings of other user with sudo

I recommend you write a 'parent' script, which can then launch the masterinstall using sudo before running myget again as the local user. Examples follows:

#!/bin/bash

sudo ./masterinstall.sh
./mygset.sh

By default sudo sets the uid and the gid to the user you've specified but it doesn't change the environment settings etc.

Suggest you try -H first, which sets the $HOME variable to the target user:

sudo -u "wang" -H ./myget.sh

If that doesn't work, try -i which is supposed to simulate the initial login.

A slightly different tack, which I've found sometimes works, is to use su:

sudo su - wang
/full/path/to/myget.sh
exit

You'll need to use the full path to the script because the su command changes the current working directory.


After trying a lot of stuff in different combinations this is the only command that worked for me:

sudo -H -u <user> DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/<uid>/bus gsettings set...

In a bash script you can use the following function to automatically detect the user and environment of a current session:

function run-in-user-session() {
    _display_id=":$(find /tmp/.X11-unix/* | sed 's#/tmp/.X11-unix/X##' | head -n 1)"
    _username=$(who | grep "\(${_display_id}\)" | awk '{print $1}')
    _user_id=$(id -u "$_username")
    _environment=("DISPLAY=$_display_id" "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$_user_id/bus")
    sudo -Hu "$_username" env "${_environment[@]}" "$@"
}

Use it like this:

run-in-user-session gsettings set...