Skip to content

Instantly share code, notes, and snippets.

@szhajdu
Last active February 3, 2024 13:27
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 szhajdu/2ba611ef5357fe7b8580384c63ed2e0c to your computer and use it in GitHub Desktop.
Save szhajdu/2ba611ef5357fe7b8580384c63ed2e0c to your computer and use it in GitHub Desktop.
Simplified version of rhukster/sphp.sh focusing only on PHP switch
#!/bin/bash
# Original version: https://raw.githubusercontent.com/rhukster/sphp.sh/main/sphp.sh
script_version=1.0.0
# Supported PHP versions
brew_array=("5.6" "7.0" "7.1" "7.2" "7.3" "7.4" "8.0" "8.1" "8.2" "8.3" "8.4")
target_version=$1
php_version="php@$target_version"
# Display help and exit if the user did not specify a version
if [[ -z "$target_version" ]]; then
echo "PHP Switcher - v$script_version"
echo
echo "Switch between Brew-installed PHP versions."
echo
echo "usage: $(basename "$0") version [-s|-s=*] [-c=*]"
echo
echo " version one of:" "${brew_array[@]}"
echo
exit
fi
homebrew_path=$(brew --prefix)
# From the list of supported PHP versions, build array of PHP versions actually
# installed on the system via brew
for version in ${brew_array[*]}; do
if [[ -d "$homebrew_path/etc/php/$version" ]]; then
php_installed_array+=("$version")
fi
done
# Check that the requested version is supported
if [[ " ${brew_array[*]} " == *"$target_version"* ]]; then
# Check that the requested version is installed
if [[ " ${php_installed_array[*]} " == *"$target_version"* ]]; then
# Switch Shell
echo "Switching to $php_version"
echo "Switching your shell"
for i in "${php_installed_array[@]}"; do
brew unlink "php@$i"
done
brew link --force "$php_version"
echo
php -v
echo
echo "All done!"
else
echo "Sorry, but $php_version is not installed via brew. Install by running: brew install $php_version"
fi
else
echo "Unknown version of PHP. PHP Switcher can only handle arguments of:" "${brew_array[@]}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment