Skip to content

Instantly share code, notes, and snippets.

@mloberg
Created October 3, 2016 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mloberg/66ec595333b4e3b99d66d222362a11c9 to your computer and use it in GitHub Desktop.
Save mloberg/66ec595333b4e3b99d66d222362a11c9 to your computer and use it in GitHub Desktop.
Bash script for managing PHP versions on macOS (using Homebrew)
#!/usr/bin/env bash
#
# Copyright (c) 2016 Matthew Loberg
# Distributed under the MIT License (http://opensource.org/licenses/MIT)
#
# ==========================
# Manage PHP (uses Homebrew)
# ==========================
#
# Commands:
# mphp list
# mphp current
# mphp switch [phpversion]
# mphp install [phpversion]
# mphp upgrade [phpversion]
#
# Requirements:
# Homebrew (http://brew.sh/)
# Homebrew PHP (https://github.com/Homebrew/homebrew-php)
currentversion=$(php -r "error_reporting(0); echo str_replace('.', '', substr(phpversion(), 0, 3));")
abort() {
(>&2 printf "\033[0;31m$1\033[0m\n")
exit 1
}
list() {
for package in $(brew list | grep 'php[0-9]\{2\}$'); do
version="${package:3}"
extra=""
if [ "${version}" == "${currentversion}" ]; then
extra="(current)"
fi
echo "* ${version} ${extra}"
done
}
switch() {
local newversion="$1"
local package="php${newversion}"
if ! $(brew list ${package} &>/dev/null); then
abort "PHP version ${newversion} was not found."
fi
brew unlink "php${currentversion}" &>/dev/null
brew link "${package}" &>/dev/null
echo "Switched to PHP ${newversion}"
}
install() {
local newversion="$1"
local package="php${newversion}"
if ! $(brew list ${package} &>/dev/null); then
brew install "${package}"
fi
echo "Installed PHP ${newversion}"
}
upgrade() {
local newversion="$1"
switch "${newversion}"
brew upgrade "${newversion}"
switch "${currentversion}"
}
if [ "$1" == "list" ]; then
list
exit
elif [ "$1" == "current" ]; then
echo "${currentversion}"
exit
fi
if [ $# -ne 2 ]; then
abort "Usage: $(basename "${0}") [command] [phpversion]"
fi
if [ "$1" == "switch" ]; then
switch "$2"
elif [ "$1" == "install" ]; then
install "$2"
elif [ "$1" == "upgrade" ]; then
upgrade "$2"
else
abort 'Valid commands are: "switch", "install", or "upgrade".'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment