Skip to content

Instantly share code, notes, and snippets.

@AlexAtkinson
Last active August 12, 2022 19:41
Show Gist options
  • Save AlexAtkinson/e5de39ea3c849aa2ffa4d7851f9d6f07 to your computer and use it in GitHub Desktop.
Save AlexAtkinson/e5de39ea3c849aa2ffa4d7851f9d6f07 to your computer and use it in GitHub Desktop.
A simple script to automatically configure some aliases for cli users.
#!/usr/bin/env bash
shell=$(awk -F/ '{print $NF}'<<<$SHELL)
# Detect target rc file.
[[ -f $HOME/.bash_profile && $shell =~ "bash" ]] && targ="$HOME/.bash_profile" # MacOS Bash
[[ -f $HOME/.zshrc && $shell =~ "zsh" ]] && targ="$HOME/.zshrc" # MacOS ZSH
[[ -f $HOME/.bashrc && $shell =~ "bash" ]] && targ="$HOME/.bashrc" # Linux
if [[ ! -n ${targ+x} ]]; then
echo "ERROR: Could not detect which rc file to modify."
exit 1
fi
targBackup="$targ.$(date -u +"%FT%H-%M-%S").bak"
cp "$targ" "$targBackup" \
&& echo "NOTICE: Your $targ file has been backed up to $targBackup!"
ls -tp $HOME/.bashrc*.bak | tail -n +5 | tr '\n' '\0' | xargs -0 rm -f -- \
&& echo "NOTICE: Only the five most recent $targ.*.bak files have been kept."
start='# RCCTRLTEST - AUTOCONFIG START ----------------------------------------------------'
content=()
content+='# WARNING: Changes to this section will be overwritten the next time\n'
content+='# '"'.\/tools\/configure-aliases.sh'"' is run.\n'
content+='# Last Updated: '"'$(date -u +"%FT%H-%M-%S")'"'\n'
content+='alias alias-foo='"'echo "foo"'"'\n'
content+='alias alias-bar='"'echo "bar"'"'\n'
end='# RCCTRLTEST - AUTOCONFIG END ------------------------------------------------------'
# Add control flags if not already present.
[[ $(grep -c "$start" $targ) == 0 ]] && echo -e "\n$start\n\n$end" >> "$targ"
# WARNING: This sed command is invalid on MacOS.
# sed: 1: "...": unterminated subsitute in regular expression
sed -ni "/${start}/{p;:a;N;/${end}/!ba;s/.*\n/${content[*]}/};p" "$targ" \
&& echo "SUCCESS: Your $targ file has been updated!" \
&& echo "NOTICE: Once your $targ file has been sourced with 'source $targ', the following commands will be available:" \
&& echo " - Run 'alias-foo' to foo" \
&& echo " - Run 'alias-bar' to bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment