Skip to content

Instantly share code, notes, and snippets.

@bskiefer
Last active April 6, 2023 14:46
Show Gist options
  • Save bskiefer/8d8215c33c7f86e7751854e710320afb to your computer and use it in GitHub Desktop.
Save bskiefer/8d8215c33c7f86e7751854e710320afb to your computer and use it in GitHub Desktop.
Automatically migrate amd64 to arm64 brew packages. Removes packages installed under /usr/local and reinstalls (if necessary) under /opt.
#!/bin/zsh
confirm=1
while getopts c flag; do
case "${flag}" in
c) confirm= ;;
esac
done
relink() {
brew unlink $BASE
brew link $BASE -n | while read -r line; do
if [[ $line = "Would link:" ]]; then
continue
fi
newPath="/usr/local"
oldPath="/opt/homebrew"
OLD_PATH=$(echo "${line/$oldPath/$newPath}")
if [[ -L "$OLD_PATH" ]]; then
rm $OLD_PATH
echo "Remove: $OLD_PATH"
fi
done
mv "/usr/local/Cellar/$BASE" "$HOME/Desktop/CellarBackup/$BASE"
brew link $BASE
}
for name in /usr/local/Cellar/*/; do
if [ -d "$name" ] && [ ! -L "$name" ]; then
oldPath="/usr/local"
newPath="/opt/homebrew"
OPT_DIR=$(echo "${name/$oldPath/$newPath}")
INSTALLED=
BASE=$(basename "$name")
if [ -d "$OPT_DIR" ]; then
INSTALLED=1
echo "Directory $OPT_DIR exists. $BASE"
else
echo "Error: Directory $OPT_DIR does not exists."
fi
if [ -z "$INSTALLED" ]; then
echo "$BASE not installed. Installing..."
brew install $BASE
else
if [ -z "$confirm" ]; then
read "response?Move old package to backups? [Y/n] "
response=${response:l} #tolower
if [[ $response =~ ^(y| ) ]] || [[ -z $response ]]; then
relink "$BASE"
fi
else
relink "$BASE"
fi
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment