0

How can I access same variables data after switching users? For example:

artifact=archive.tar.gz
workdir=/home/user

echo "$workdir/$artifact"
sudo -u otheruser bash
echo "$workdir/$artifact"

Produces:

/home/user/archive.tar.gz
/

Is it possible that second echo would resolve in same path as the first one?

Edit: Complete solution, thanks to @Romeo Ninov and @steeldriver:

export artifact=archive.tar.gz
export workdir=/home/user

echo "$workdir/$artifact"
sudo -Eu otheruser bash
echo "$workdir/$artifact"
  • The sudo in your script would start a new shell. The remainder of the script would run as the original user once that shell exits. There is no way to "switch users" in the middle of a shell script. – Kusalananda Jan 22 at 13:55
  • 1
    As is, you should get the proper variable twice, sudo -u otheruser bash will fork a new bash without wanted values, but when you exit, "$workdir/$artifact" should be the same. – Archemar Jan 22 at 14:36
0

Export the variables:

export artifact=archive.tar.gz
export workdir=/home/user
  • 3
    Whether that works or not will depend on the sudoers env_reset / env_keep policy I think - and may require addition of -E (or --preserve-env)? – steeldriver Jan 22 at 13:58
-1

You may want to use zsh instead of bash which has support for changing uids and gids (provided it is started with super-user privileges):

#! /bin/zsh -
id
echo "Original user: $SUDO_USER"
var=test
(
  USERNAME=$SUDO_USER
  echo "Runing as $(id -un) in this subshell var=$var"
)
(USERNAME=nobody; echo and now:; id; echo $var)

Running as:

$ sudo ./that-script
uid=0(root) gid=0(root) groups=0(root)
Original user: stephane
Runing as stephane in this subshell var=test
and now:
uid=65534(nobody) gid=65534(nogroup) groups=65534(nogroup)
test

Setting USERNAME sets the uid, euid, gid, egid and supplimentary gids as if logging in or using sudo. You can also set the UID/EUID/GID... variables individually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.