2

I have a simple very tiny web app, and wanted to make my life a bit easier by having a very simplistic deployment script, that does the following:

  1. Pull updates from git
  2. Run composer
  3. Change owner of all files

The script basically works fine and looks like this:

#!/bin/bash
echo "Updating repository ...";
sudo git pull;

echo "Installing composer dependencies from lockfile ...";
composer install;

echo "Changing owner to www-data:www-data ...";
sudo chown -R www-data:www-data .;

echo "Deployment DONE!";

However, as you can see, I have two commands run as sudo in this script. Nameply the git pull and the chown.

My problem is as follows: I am aware that there is a timeout for how often the system asks for my password when running commands with sudo. The problem is, that, even though I am well within the timeout, the script always asks for the password on the second sudo (chown) command.

Could someone please enlighten me, why that may be the case?

cat
  • 1,672
ArSeN
  • 121
  • You know lines don't need to end with ;s, right? You just like it 'cause you're a Real C Programmer who eats pointers to pointers to pointers to pointers for breakfast? – cat May 07 '16 at 22:49
  • 1
    @cat Yes I know. I like doing it like that because it looks "cleaner" to me *shrug – ArSeN May 08 '16 at 09:29

2 Answers2

1

I don't really know what's the reason, however there's solution:

if [[ $(id -u $(whoami)) != 0 ]]
then
    sudo bash $( cd $(dirname $0) ; pwd -P )
    # taken from http://stackoverflow.com/a/4774063/2797066
else
    #rest of script
fi
enedil
  • 982
  • 5
  • 15
  • 27
1

Why don't you run script with sudo like this:

sudo bash /path/to/script.sh

Where script.sh has following content with no sudo:

#!/bin/bash
echo "Updating repository ...";
git pull;

echo "Installing composer dependencies from lockfile ...";
composer install;

echo "Changing owner to www-data:www-data ...";
chown -R www-data:www-data .;

echo "Deployment DONE!"

This way script will only ask you for password for 1 time.

snoop
  • 4,040
  • 9
  • 40
  • 58
  • I thought about that too. However I want to avoid running composer with sudo, as this is discouraged. Thats why I don't want to run the whole script with sudo. – ArSeN May 07 '16 at 17:48