Reputation: 43
To make sure my bash script runs as root I use:
if [ "$UID" -ne "0" ]; then
echo "You must root to run $0. Try following"
echo "sudo $0"
exit 9
fi
But in the script, there some commands that I want to run with sudo -u $USER
, however, if I run the whole script as root it comes out as sudo -u root ($USER will be root, not the original USER).
How do I run the script as root but also run certain commands in the script as the default logged in user so I don't have to put in the password or do chmod
to change permissions?
Upvotes: 0
Views: 1888
Reputation: 20032
You need the non-evaluated user in some variable.
How you want to do this depends on your actual use case.
You can look at:
Nasty temp file:
echo "$USER" > /tmp/thatsme.tmp
su -
# Hmm, now hope nobody has changed the tmpfile doing the same trick
orguser=$(cat /tmp/thatsme.tmp)
rm /tmp/thatsme.tmp
Keep environment
export orguser="$USER"
su # Not su -
echo "orguser=${orguser}"
Proces ps -ef
and look for original user on the same tty you are on. (not recommended)
Call su - -c script additional parameter
and change your master script that it pulls the user from $1
.
Upvotes: 1
Reputation: 11
Within your bash script you'll need to use the 'su' command to switch user, then the -c command with your needed command/script.
If you run as root you won't need to put in the $USER password.
Example: su $USER -c "command"
Upvotes: 1