Created
November 8, 2021 10:20
-
-
Save infostreams/3753a31205e3b6c47039046e9fa40ba5 to your computer and use it in GitHub Desktop.
Change PHP version on MacOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
available=$(brew list --formula -1 | egrep '^php@|^php$') | |
syntax () { | |
echo "SYNTAX: $0 <version>" | |
echo "" | |
echo -n "<version> needs to be one of: " | |
echo $available | |
echo "" | |
echo "Choose the latest version of PHP by naming 'php' as the version" | |
exit 2 | |
} | |
# check if enough arguments | |
if [ "$#" -ne 1 ]; then | |
syntax | |
fi | |
version=$(echo "${available}" | grep "${1}" | head -n 1) | |
# check if valid version | |
if [[ -z "$version" ]]; then | |
syntax | |
fi | |
# do it | |
echo "Will use version $version" | |
echo $available | xargs brew unlink | |
# first default to a known 'safe' version, | |
# otherwise we cannot always do the change | |
brew link php@7.4 | |
valet use php@7.4 --force | |
# now change to the requested version | |
valet use "$version" --force |
Updated script for users who don't use valet (or rather, it's not in search PATH).
It's not enough to simply comment out the two valet lines, since that will always end up linked to php@7.4
Also checks that you are not actually requesting php@7.4, which would generate an 'already linked' warning
#!/bin/bash
available=$(brew list --formula -1 | egrep '^php@|^php$')
syntax () {
echo "SYNTAX: $0 <version>"
echo ""
echo -n "<version> needs to be one of: "
echo $available
echo ""
echo "Choose the latest version of PHP by naming 'php' as the version"
exit 2
}
# check if enough arguments
if [ "$#" -ne 1 ]; then
syntax
fi
version=$(echo "${available}" | grep "${1}" | head -n 1)
# check if valid version
if [[ -z "$version" ]]; then
syntax
fi
# do it
echo "Will use version $version"
echo $available | xargs brew unlink
# first default to a known 'safe' version,
# otherwise we cannot always do the change
brew link php@7.4
valet_bin=`which valet`
if [ -z "${valet_bin}" ]; then
if [ "${version}" != "php@7.4" ]; then
brew link "${version}"
fi;
exit
fi;
valet use php@7.4 --force
# now change to the requested version
valet use "$version" --force
@infostreams Thanks, this was really useful for me as I also use Laravel Valet. To run the script I did the following:
$ chmod +x php.sh
$ ./php.sh php@7.4
- Enter sudo password
Notice having to use the @
symbol to install a PHP version as it didn't work first time around.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The change to PHP7.4 is unfortunately necessary because you cannot otherwise safely change between PHP 5.x and other versions of PHP.
Note that this script uses valet as well. If you don't use that, simply delete these two lines.