1

I have such a bash script:

#!/bin/bash                                                              

cd /home/user/projekt
git config core.sparseCheckout true
git pull origin master
wait
rm -rf /var/www/project/{client,public}
cp -r /home/user/project-checkout/project/dist/* /var/www/project/
cd /var/www/project/
npm install

Since I must run the copy and the npm install commands with elevated rights, I run the bash script with sudo.

However - git pull does not work as sudo since it reads form the users .gitconfig and .sshconfig files. IT says "Please make sure you have correct access rights" as expected when doing a git sudo

How to solve? I was thinking in side the script de-elveate right for one commend - possible?

As a bonus, how can I tell my script to only pursue after line 3 has successfully finished?

2 Answers 2

1

Instead of de-elevating, you could only sudo where necessary; so in your script:

...
sudo cp ...
cd /var/www/project
sudo npm install

You can use

set -e

at the start of your script to cause any error to stop the script, which would have the desired effect on line 3. I'm not sure why you need the wait there though; git pull will only return once it's finished working.

4
  • Indeed wait seems to become unncessary with the set -e option. I though using sudo within bash script is bad practice?
    – user46399
    Commented Mar 5, 2015 at 0:44
  • I think it is bad practice to use it in a script as shown because the user will see a request for a password and have no idea why. Better would be echo "I need root permissions so I can copy your file foo to /var/www/project where anyone in the world can see it" and suchlike. I think better still would be echo the commands needed and let the user execute them manually. I'd be wary of scripts that prompt me for my password and have to read it or uninstall it.
    – msw
    Commented Mar 5, 2015 at 7:08
  • Generally speaking yes, but in this case the user of the script is the author of the script, so trust shouldn't be an issue. It would be better to add an explanation before the sudo, or split the script into a build script and an install script; I'll update my answer accordingly later. Commented Mar 5, 2015 at 8:32
  • Interesting... I now ended up using grunt and sshexec to remotely connect to the machine. I gave permissions to my .npm folder, and now I dont have to sudo anymore.
    – user46399
    Commented Mar 5, 2015 at 19:55
0

Check out this gist , there are multiple ways to do it ... The first one worked best when I had that same issue .LINK

You can also add the set -x to see you script in action.

You must log in to answer this question.