Skip to content

Instantly share code, notes, and snippets.

@alpipego
Last active December 13, 2023 05:10
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 alpipego/ec45d35e1fdc3dc10a5cbe821f588800 to your computer and use it in GitHub Desktop.
Save alpipego/ec45d35e1fdc3dc10a5cbe821f588800 to your computer and use it in GitHub Desktop.
Streamline Homebrew search-info-install
#!/bin/bash
# Function to prompt for package installation
prompt_install() {
local pkg=$1
brew info "$pkg"
read -p "Do you want to install $pkg? [Y/n] " answer
if [[ "$answer" == "Y" ]] || [[ "$answer" == "y" ]] || [[ -z "$answer" ]]; then
brew install "$pkg"
else
echo "Installation cancelled for $pkg."
return 1
fi
}
# Fetch the list of installed packages once
INSTALLED=($(brew list))
# Get the package name from the argument
PKG=$1
# Search for the package using brew
SEARCH=$(brew search "$PKG" 2>/dev/null)
# Creating an array of packages that matched the search and mark installed ones
IFS=$'\n'
PACKAGES=()
for PACKAGE in $SEARCH; do
# Check if the package is already installed and add a checkmark accordingly
if printf '%s\n' "${INSTALLED[@]}" | grep -qx "$PACKAGE"; then
PACKAGES+=("$PACKAGE ✔︎")
else
PACKAGES+=("$PACKAGE")
fi
done
unset IFS
# If there are no matches, show an error message
if [ ${#PACKAGES[@]} -eq 0 ]; then
echo "No packages found for $PKG."
elif [ ${#PACKAGES[@]} -eq 1 ]; then
# If there is only one match, show the info and ask for confirmation
prompt_install "${PACKAGES[0]%% *}"
else
# If there are multiple matches, present a list and let the user choose
while true; do
echo "Multiple packages found. Select a package to install:"
COLUMNS=1
select CHOICE in "${PACKAGES[@]}"; do
if [[ -n "$CHOICE" ]]; then
CHOICE="${CHOICE%% *}" # Remove the checkmark (if any) before installing
if prompt_install "$CHOICE"; then
break 2
else
break
fi
else
echo "Invalid choice. Please enter a valid number."
fi
done
done
fi
@alpipego
Copy link
Author

Use this bash script to streamline your Homebrew package installation process. It searches for a package, presents install options, and simplifies batch installations with user confirmation for macOS.

Installation Instructions:

  1. Download the script file.
  2. Move the script to a directory in your $PATH: mv /path/to/script.sh ~/.local/bin/.
  3. Make the script executable: chmod +x /path/to/script.sh.
  4. Run it using script.sh <package-name> from any terminal window.

For detailed usage and explanation, check out the blog post: https://www.alexandergoller.com/journal/14694/streamline-homebrew-search-info-install

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