Last active
April 13, 2022 00:21
-
-
Save dnedrow/261743f66f01e5713759f217fd0abbba to your computer and use it in GitHub Desktop.
Shell script for backing up the list of installed Homebrew (brew) packages
This file contains hidden or 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/zsh -l | |
| # This script can easily be added to your crontab for scheduled backups. | |
| # | |
| # EXITS | |
| SUCCESS=0 | |
| BUNDLE_FAILED=1 | |
| BACKUP_FILE_EXISTS=2 | |
| MOVE_FAILED=3 | |
| NO_HOMEBREW=4 | |
| set HOMEBREW_PREFIX | |
| BREW_ARM_PREFIX=/opt/homebrew | |
| BREW_X86_PREFIX=/usr/local | |
| BREWFILES=~/Brewfiles | |
| ARCH=$(arch) | |
| if [[ ${ARCH} == "arm64" ]]; then | |
| HOMEBREW_PREFIX="${BREW_ARM_PREFIX}" | |
| else | |
| HOMEBREW_PREFIX="${BREW_X86_PREFIX}" | |
| BREWFILES=$BREWFILES-x86 | |
| fi | |
| [ ! -d ${HOMEBREW_PREFIX} ] && exit $NO_HOMEBREW | |
| BREWBIN="${HOMEBREW_PREFIX}/bin/brew" | |
| cd ~ | |
| if [ ! -d $BREWFILES ]; then | |
| mkdir -p $BREWFILES | |
| fi | |
| if [ -f ~/.Brewfile ]; then | |
| echo ~/.Brewfile already exists. Remove this file and try again. >&2 | |
| exit $BACKUP_FILE_EXISTS | |
| fi | |
| #Update everything | |
| # ${BREWBIN} update > /dev/null 2>&1 && exit 5 | |
| $BREWBIN bundle dump --describe --global > /dev/null 2>&1 | |
| BREW_EXIT=$? | |
| if [ "$BREW_EXIT" -ne "0" ]; then | |
| echo Brew bundle dump failed with return code: $BREW_EXIT >&2 | |
| exit $BUNDLE_FAILED | |
| fi | |
| unset BREW_EXIT | |
| DATE=$(date +"%Y%m%d-%H%M%S") | |
| if [ -e ~/.Brewfile ]; then | |
| mv ~/.Brewfile $BREWFILES/Brewfile-${DATE}; | |
| BREW_EXIT=$? | |
| if [ "$BREW_EXIT" -ne "0" ]; then | |
| echo The mv command failed with exit code: $BREW_EXIT >&2 | |
| echo You should mv or rm ~/.Brewfile before running this script again. >&2 | |
| exit $MOVE_FAILED | |
| fi; | |
| fi; | |
| exit $SUCCESS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment