I am writing some bash scripts to install and configure some programs.
Because the script needs to install packages - I run the scripts as root - which itself is no problem (ie I have root privileges etc).
However once the packages are installed the script needs to configure normal user files and fetch plugins etc, eg
sed is/xxx/mod_to_make/ <user_config_file>
git clone <plugin>
wget <plugin>
Ideally I would do this as a regular user because I don't want these git repos and files to be owned by root,
An example program snippet is something like
#! /bin/bash
# Because this statement needs to be run as root - the entire script is
# also run as root
apt-get install -y tmux
cat << EOF > ~/.tmux.conf
#
# config stuff
#
EOF
Do I need to manually revert file privileges to regular user, at the end of the script, eg
chown $USER:$USER ~/.tmux.conf
chmod 755 ~/.tmux.conf
Or write 2 separate scripts 1 run by a root the other as regular user ?
Or is there a better way to handle this?
Just because we usually associate sudo as a means to become root, it doesnt mean it cannot be used by root to become a user.
So just prefix the commands you need to run as $USER by
sudo -u $USER ....
To make it easier to have all in one script, collect all the root code into a function and all the user code into another function, then run the script as root, and it can then run the same script as USER. We check the id of the person running the script and do one function or the other. eg:
#!/bin/bash
rootstuff(){
....
[ "$USER" != root ] && sudo -u $USER $0
}
userstuff(){
....
}
if [[ $(id) = uid=0* ]]
then echo root
rootstuff
else echo user
userstuff
fi
Make sure USER is not root.
If you have a bunch of consecutive codes which should be run as regular user (not root), then you can do this:
sudo -s -u $USER<<EOF
echo "running codes as normal user"
EOF
Note: You may need to check if $USER
is a regular user or root. If you run the script in a root shell, the value of $USER
will be root
and that's the normal and expected behavior, ie whatever user specific files you are creating are expected to be created in the root environment.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.