Skip to content

Instantly share code, notes, and snippets.

@moqmar
Last active January 31, 2019 12:38
Show Gist options
  • Save moqmar/450ac6592028c742177bae71705e6e16 to your computer and use it in GitHub Desktop.
Save moqmar/450ac6592028c742177bae71705e6e16 to your computer and use it in GitHub Desktop.
Bash script to apply a text file with a list of packages to add (package) and remove (!package) to an Arch-based system using yay. Written to keep two computers in sync, but can be used for a lot of purposes. The packages can be separated using spaces or newlines; line comments starting with # are supported, too.
#!/bin/sh
set -eu
IFS=$'\n\t'
# Bash script to apply a text file with a list of packages to add (package) and remove (!package) to an Arch-based
# system using yay. Written to keep two computers in sync, but can be used for a lot of purposes.
# The packages can be separated using spaces or newlines; line comments starting with # are supported, too.
# The packages file can be defined as a command line argument.
# Otherwise, it'll be taken from $XDG_PUBLICSHARE_DIR/packages.
[ ! -f ~/.config/user-dirs.dirs ] || source ~/.config/user-dirs.dirs
[ -z "$XDG_PUBLICSHARE_DIR" ] || packagefile="$XDG_PUBLICSHARE_DIR/packages"
[ $# -lt 1 ] || packagefile="$1"
# Loop through packages file without comments and spaces.
install=
remove=
for pkg in $(sed -E -e 's/\s*#.*$//g' -e 's/^\s+//g' "$packagefile" | sed -E ':a;N;$!ba;s/\s+/\n/g'); do
# Check if it's already installed.
installed=1
yay -Q "$(echo "$pkg" | sed 's/^!//')" >/dev/null 2>&1 || installed=0
# Add package to install/remove list if required.
if echo "$pkg" | grep '^!' >/dev/null; then
if [ $installed -eq 1 ]; then
remove="$remove"$'\n'"$(echo $pkg | sed 's/^!//')"
fi
elif [ $installed -eq 0 ]; then
install="$install"$'\n'"$pkg"
fi
done
# Print a summary and ask for confirmation
if [ -z "$install" ] && [ -z "$remove" ]; then
echo "Nothing to do."
exit 0
fi
echo "Packages to install:$(echo "$install" | sed ':a;N;$!ba;s/\n/ /g')"
echo "Packages to remove: $(echo "$remove" | sed ':a;N;$!ba;s/\n/ /g')"
echo -n "Continue? (Y/n) "
read -n1; echo
if [ "$REPLY" != "Y" ]; then
exit 1
fi
# Apply everything
[ -z "$install" ] || yay -S $install
[ -z "$remove" ] || yay -Rucs $remove
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment