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 (i.e. I have root privileges etc).
However once the packages are installed the script needs to configure normal user files and fetch plugins etc, e.g.
sed i s/xxx/mod_to_make/ <user_config_file>
git clone <plugin>
wget <plugin>
- etc
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, e.g.
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?
Advertisement
Answer
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, i.e whatever user specific files you are creating are expected to be created in the root environment.