Bash Script To Update Drupal Modules In A Single Command

If you run a lot of Drupal update then you will probably have written the commands for composer update, running database updates, and exporting the configuration.

To assist in this I put together this bash script that will perform the following actions.

  • Update the package using composer.
    • If the update produced no response then we exit here.
    • If it did produce a response then we save the version updates so we can print it out later.
  • Run the drush updatedb command to perform any database updates.
  • Export the new configuration with the drush cex command.
  • Print the commit message that includes what module was updated and what the version was.

Here's the script.

#!/bin/bash

if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <ticket number> <module name>"
    exit 1
fi

cd $PWD > /dev/null

TICKET_NUMBER="$1"
PACKAGE_NAME="$2"
COMPOSER_UPDATE_VERSION="";

# Update module in composer.
COMPOSER_OUTPUT=$(composer update $PACKAGE_NAME -W 2>&1)

REGEX_PATTERN="(Upgrading $PACKAGE_NAME \(([^=]+)=>([^\)]+)\))"

# Attempt to extract the relevant information out of the composer update notice.
if [[ "$COMPOSER_OUTPUT" =~ $REGEX_PATTERN ]]; then
    COMPOSER_UPDATE_VERSION=${BASH_REMATCH[1]}
    echo "Composer update successful : $COMPOSER_UPDATE_VERSION"
fi

UPDATE_STATUS=$?
if [ $UPDATE_STATUS -ne 0 ]; then echo "Composer update failed."; exit 1; fi

# Run drush update database commands.
./vendor/bin/drush updatedb -y

UPDATE_STATUS=$?
if [ $UPDATE_STATUS -ne 0 ]; then echo "Drush update failed."; exit 1; fi

# Export any new configuration.
./vendor/bin/drush cex -y

UPDATE_STATUS=$?
if [ $UPDATE_STATUS -ne 0 ]; then echo "Drush config export failed."; exit 1; fi

# Add the changes to git.
git add composer.lock composer-manifest.yaml
git add config/.

UPDATE_STATUS=$?
if [ $UPDATE_STATUS -ne 0 ]; then echo "Git add failed."; exit 1; fi

# Print out the update message (if we have one).
if [[ -n $COMPOSER_UPDATE_VERSION ]]; then
  echo ""
  echo "$TICKET_NUMBER: $COMPOSER_UPDATE_VERSION."
  echo ""
fi

cd - > /dev/null

Just copy this script into a file called "update.sh" and make it executable with the command chmod -x update.sh.

To use the script do something like the following to update the Redirect module as part of the .

./update.sh 123 drupal/redirect

This will run through the composer, Drush update and configuration export actions and finally show a commit message that you can use.

123: Upgrading drupal/redirect (1.11.0 => 1.12.0).

This has been quite extensively tested, but doesn't support multi sites.

If you are running ddev then you can run this using the following command.

ddev exec ./update.sh 123 drupal/redirect

Add new comment

The content of this field is kept private and will not be shown publicly.