1

I am logged in as root and want to execute a Bash script with sudo permissions as another user.

This is the test Bash script in /home/me/sudo.bash:

mkdir -p /etc/test # Creating an /etc directory to test permissions
echo "test $(whoami) $USER $HOME" > /etc/test/a.txt

The command I currently have (run from root, run for me):

sudo --non-interactive --login --set-home --user=me \
sudo --non-interactive bash /home/me/sudo.bash

Contents of /etc/test/a.txt:

test root root /home/me

What I expected:

test me me /home/me

What am I doing wrong here?

  • The first sudo in that runs the given command as me, that command being another sudo, which runs the given command as root, which is bash with your shell script. What did you expect from the second sudo? – muru Nov 27 '18 at 8:21
  • @muru Yes, this may be overcomplicated, but I didn't find a more simple way yet. The first sudo is for switching the user to me, the second sudo is for running the Bash script with elevated permissions, so I can create a directory in /etc. – Jaid Nov 27 '18 at 8:27
  • sudo without --user always runs command as uid root, what he expects (use uid me and has sudo privilege) is not correct. – Alvin Liang Nov 27 '18 at 8:28
  • That makes no sense. "Elevated permissions" usually mean running as root; so you want your script to be run as me and root at the same time? – muru Nov 27 '18 at 8:30
  • 1
    Why not just let your script create directory and file with root permission, and then change the owner to me, then use me to modify the content. – Alvin Liang Nov 27 '18 at 8:32
0

This is expected, that $(whoami) will return "root", since it's running as root due to the second sudo.

Also, $USER will return "root" because sudo always sets that variable to the target user (which, again, is root on the second sudo.)

If you're interested in knowing which user invoked sudo, which would be "me" on the case of the second sudo, then look at the $SUDO_USER variable, which sudo sets to the user who invoked it.

See SUDO_USER and USER in the "Environment" section of the sudo man page.

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.