Search code examples
linuxbashrootsudosudoers

Switching back to previous user after "sudo -i" using Bash


I want to add a super user to /etc/sudoers by running a script and then continuing installation. Therefore, I need to switch the user back to the original user from root after adding the user. Here is what I got:

...
current_user=$(whoami)
sudo -i
sudo echo "www-data ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
sudo su $current_user 
...

Unfortunately the last line does not work, since $current_user is null for some reason. Any guidance as to what might be the problem would be appreciated.

Best,


Solution

  • sudo -i is for interactive use, to run a simple command as root, you just add sudo in front of it. In this case, since we want to pipe to a file that requires elevated permissions, we should run the shell as sudo. The commands in the questions could be written as:

    ...
    sudo bash -c 'echo "www-data ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers'
    ...