When logging into the Ubuntu system, the login user is "root
".
And then, I want to execute some bash script on behalf of the "non_root
":
root@test_pc:~# echo $USER
root
root@test_pc:~# sudo -E -u non_root -g non_root -H /bin/bash -c "echo $USER"
root
root@test_pc:~#
But the output is still "root
", in other words, the command is still execute under "root
" user instead of "non_root
".
Here is the expected output:
root@test_pc:~# sudo -E -u non_root -g non_root -H /bin/bash -c "echo $USER"
non_root
root@test_pc:~#
Here is the real operation:
sudo -E -u non_root -g non_root -H /bin/bash -c "systemctl --user disable pulseaudio.service"
But got the following error:
Failed to connect to bus: Operation not permitted (consider using --machine=<user>@.host --user to connect to bus of other user)
How to execute any bash command as "non_root
" when logged in with "root
" user?
Needless to say that what you're doing i.e. logging in as the user
root
is discouraged and therefore theroot
user is disabled by default on Ubuntu.That said, ...
Double quotes around the Bash command string allow for parameter expansion in the current shell on the current command line before the command gets executed … see it in action:
While your command is actually executed as the intended user:
To expand
$USER
in the sub-shell created to run that Bash command string instead use single quotes around the command string instead:Notice as well that pulseaudio is a user service that requires user login to run ... See for example https://askubuntu.com/a/1465201 and Dbus is also part of the user’s user-runtime environment and requires a user login as well ... See for example https://askubuntu.com/a/1470118