sudoswitch-user

one-liner to become another user and run a command as that user


In my local machine, I would like to become another user (let's say currently I am user_c) and then to run a command as that user, specifically I would like to become user_o and run whoami.

I usually do this in two lines like so:

sudo -i -u -user_o         # Note: no password is needed to run this command
whoami

Now, how to do it one-liner?

I have tryed

sudo -i -u user_o && echo "$(whoami)"

but it just becomes user_o.

I have also tryed this

sudo -i -u user_o echo "$(whoami)"

but it just prints the current user, like it is ignoring the sudo -i -u user_o command

user_c

also runuser does not work since user_c is not user root in my case:

runuser -l user_o -c 'echo "$(whoami)"'

runuser: may not be used by non-root users

Solution

  • SOLVED

    actually there is no need to use && to separate the "switch user" command and the command that one wants to be executed as the target user.

    sudo -i -u user_o whoami