-1

I have bash-script that uses sudo commands, but in the middle I need to stop sudo-influence and then later reinstate it.

Very simple version using Pseudo code

sudo apt-get install -y synaptic
sudo ...
// I need to suspend sudo here, otherwise the folder 
// is created with root as the owner.
mkdir ~/mystuff
// then reinstate it here
sudo apt-get install -y ssllib

Does sudo request the passphrase as soon as it starts to run a bash script - or- does it only ask when it encounters the first "sudo" line?

If so, then I think I may be able to move all the non-sudo stuff to the top. But, the problem there is I will have to wait until the first "sudo" line is encountered to then enter the passphrase.

2 Answers2

2

sudo offers the option -u for that, see man sudo:

-u user, --user=user
 Run the command as a user other than the default target user (usually root).
 The user may be either a user name or a numeric user ID(UID) prefixed
 with the ‘#’ character (e.g.  #0 for UID 0).  When running commands as a UID,
 many shells require that the ‘#’ beescaped with a backslash (‘\’).
 Some security policies may restrict UIDs to those listed in the password
 database. The sudoers policyallows UIDs that are not in the password database
 as long as the targetpw option is not set. Other security policies may
 not support  this.

For your example this would be:

sudo -u USERNAME mkdir /home/USERNAME/mystuff
Eliah Kagan
  • 119,640
dessert
  • 40,956
2

Given your current script, no, the mkdir command won't be run with sudo. sudo doesn't magically start affecting commands which it does not start. Nor does it magically ask for password before it is ever run.

What might be happening is that you might have run your entire script with sudo. If that's the case, then you can check if that's true, and either ask the user to run it without sudo:

if [ -n "$SUDO_COMMAND" ]
then
    echo "Please don't run this script with sudo."
    exit
fi

Or, switch to the actual user for these commands:

if [ -n "$SUDO_USER" ]
then
    sudo -iu "$SUDO_USER" sh -c 'mkdir ~/mystuff'
fi

You might need the sh -c because ~ is expanded by the shell running the script, and depending on sudo settings, that shell might think the home directory is root's.

muru
  • 207,228