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,632
  • 1
  • 24
  • 47
ArSeN
  • 121
  • 4
  • 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
    The script asks for the password on the second sudo command because Composer always calls `sudo -k`, invalidating the user's cached credentials. An environment variable, COMPOSER_ALLOW_SUPERUSER, may be used to disable automatic clearing of sudo sessions. Make sure you understand the security implications before using this. See [https://getcomposer.org/doc/03-cli.md#composer-allow-superuser](https://getcomposer.org/doc/03-cli.md#composer-allow-superuser). – TooManyPets Mar 18 '17 at 12:33
  • @TooManyPets Your comment should be an answer, it's a clear explanation with a tip how to fix it! – JohnEye May 07 '19 at 12:42
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,030
  • 8
  • 39
  • 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