I have a large bash script that is supposed to install all dependencies for an application and then build the application itself.

I run the script with sudo because most of the commands require it, e. g.:

apt update
apt install -y libunwind8
apt install -y curl

Then it gets to building the application:

npm install
npm run build

When the script gets to these two commands it fails, giving me the following error:

/home/crispjam/.npm/_cacache/tmp/git-clone-98eb9fb8/.git: Permission denied

I did some research on this and found out that when interacting with a git repository you shouldn't use sudo.

I tried running the npm install outside of the script and it did, indeed, work, suggesting that sudo makes that command fail inside the script.

I've considered adding sudo to all the commands inside instead of running the script with sudo but I've read here that for the most part it is not considered good practice.

In the top answer I read that you can drop the sudo privileges from a single command by prepending sudo -u username to it.

Is this good practice?

And how can I make this dynamic so that instead of using my username the script uses the name of the user running the script?

  • Related: Ignore sudo in bash script - if the script is being run via sudo, then it should be able to access the invoking user's uersname as $SUDO_USER Mar 29, 2019 at 12:49

2 Answers 2


Have you considered changing the folder permissions?

You can check it by right-clicking properties on the folder in your file explorer.


One of the answers here suggested using the command logname, which prints the user's login name.

To use it inside the script I simply modify the lines

npm install
npm run build


sudo -u $(logname) npm install
sudo -u $(logname) npm run build

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .