How to write version-agnostic bash scripts for PHP

Many PHP module and service names include the target version of PHP: php7.3-fpm, for example. This makes it difficult to write portable bash scripts, or Laravel Forge recipes.

Symlinks solve some of these problems, but can be painful to maintain. A cleaner solution is to determine the current PHP version programmatically. Here’s how to do that.

# Figure out the PHP MAJOR.MINOR version
php_version=`php -r "echo PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION;"`

# Use the PHP version in a command
sudo service "php${php_version}-fpm" restart

Sign up for my newsletter

A monthly round-up of blog posts, projects, and internet oddments.