Skip to content

Instantly share code, notes, and snippets.

@negativems
Last active January 31, 2023 12:21
Show Gist options
  • Select an option

  • Save negativems/c403fb25df9d0d58456f233589dca375 to your computer and use it in GitHub Desktop.

Select an option

Save negativems/c403fb25df9d0d58456f233589dca375 to your computer and use it in GitHub Desktop.
CLI commands to list and switch between PHP versions

image

Usage

  • php-versions # Find all installed php versions in laragon folder (configurate)
  • php-switch <version/lastest> # Switch to a php version changing env variables ($PATH)

Script

Put this on your .bashrc (NOTE: This script is made to use in Windows with Git Bash)

# The folder where you have all the PHP versions
PHP_FOLDER="/c/laragon/bin/php"

# List all PHP versions
# alias php-versions="ls -1 $PHP_FOLDER | cut -d'-' -f2 | sort -u"

# Create alias like php-versions but in the last version put "lastest" in parenthesis (7.4.1 => 7.4.1 (lastest))
php-versions() {
   versions=$(ls -1 $PHP_FOLDER | cut -d'-' -f2 | sort -u)
   lastest=$(ls -1 $PHP_FOLDER | cut -d'-' -f2 | sort -u | tail -n 1)

   for version in $versions; do
      if [ "$version" = "$lastest" ]; then
         echo "$version (lastest)"
      else
         echo "$version"
      fi
   done
}


# Switch PHP version
php-use() {
   if [ -z "$1" ]; then
      echo "Usage: php-switch <version>"
      return
   fi

   # Check if PHP command exists
   if ! command -v php &> /dev/null; then
      previous="none"
   else
      previous=$(php -v | head -n 1 | cut -d' ' -f2)
   fi

   version=$1

   # Check if version is "lastest"
   if [ "$version" = "lastest" ]; then
      version=$(php-versions | tail -n 1 | cut -d' ' -f1)
   fi

   # Check if PHP version is already that version
   if [ "$version" = "$previous" ]; then
      echo "PHP version $version is already active"
      return
   fi

   # Check if the new version exists
   PHP_FILE=$(ls -1 /c/laragon/bin/php | grep $version | head -n 1)
   if [ -z "$PHP_FILE" ]; then
      echo "PHP version $version not found"
      return
   fi

   # Get previous PHP path
   PHP_PREV_FILE=$(ls -1 /c/laragon/bin/php | grep $previous | head -n 1)

   # Change PHP version in env path
   export PATH="/c/laragon/bin/php/$PHP_FILE:$PATH"

   echo "Using php $version"
}

php-use lastest
@negativems
Copy link
Copy Markdown
Author

Not working inside vscode terminal, idk why, I am not a bash programmer btw, copilot made the most part

@negativems
Copy link
Copy Markdown
Author

Now is working in vscode terminal ๐Ÿ‘

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment