Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a command as the standard user, from a sudo elevated script

If a bash script has been executed with sudo, how can a command within the script run as the currently logged in user, instead of root and then revert to root to continue running other commands?

For example: -

#!/usr/bash

touch fileOwnedByRoot.txt
touch fileOwnedByUser.txt
touch otherRootFile.txt

If this script is run with sudo, without changing the order of commands, how can the 2nd touch command be run as the standard user?

The script is only a simple example, so using chmod to change ownership of files created is irrelevant.

The actual script I'm using is being run by an installer, so running with elevated privileges is a requirement, but specific commands must be run as the user running the installer, whose name is not known.

like image 440
TheDarkKnight Avatar asked Dec 02 '25 21:12

TheDarkKnight


2 Answers

Use su - another_user -c "<command>" to run that specific command:

#!/bin/bash

touch /tmp/f1
su - another_user -c "touch /tmp/f2"
touch /tmp/f3

As commented by chepner below, you need to use $SUDO_USER or $SUDO_UID to get the name of the real user running the sudo command:

su - $SUDO_USER -c "touch /tmp/f2"

This way, the file will be touched by the user running the command.

You can test with:

#!/bin/bash
echo "sudo_user: $SUDO_USER"
echo "sudo_uid: $SUDO_UID"

And run the script either with ./script or sudo ./script. In the second case the values will be populated.

like image 167
fedorqui 'SO stop harming' Avatar answered Dec 04 '25 15:12

fedorqui 'SO stop harming'


Don't run the script as sudo, just the commands that require elevated privileges.

#!/bin/bash
sudo touch fileOwnedByRoot.txt
touch fileOwnedByUser.txt
sudo touch otherRootFile.txt
like image 25
chepner Avatar answered Dec 04 '25 17:12

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!