Skip to content

Instantly share code, notes, and snippets.

@bompus
Last active October 30, 2021 18:06
Show Gist options
  • Save bompus/58f46c28ee4adc1b2fb1b3a292a5567d to your computer and use it in GitHub Desktop.
Save bompus/58f46c28ee4adc1b2fb1b3a292a5567d to your computer and use it in GitHub Desktop.
bash local aliases / per-directory aliases in bash
// download .bash_local_aliases file and cd to the download directory
$ cp .bash_local_aliases ~/
$ if ! grep -qF 'source ~/.bash_local_aliases' ~/.bashrc; then echo -e "\nsource ~/.bash_local_aliases" >> ~/.bashrc; fi
$ source ~/.bash_local_aliases && cd .
// place a .aliases file anywhere, in the space-delimited "alias command" format shown in the .aliases example in this gist
// IMPORTANT: .aliases file should end with a single blank, empty line
$ cd .
$ myNode -e 'console.log(process.execArgv)'
$ nv
// place a different .aliases file in another directory
// then `cd` to it, and experience the magic of per-directory bash aliases
myNode node --experimental-json-modules --no-warnings
nv node -v
function _brunner_runMethod() {
if [ "$1" != "/" ]; then
# traverse up directory tree, deepest directory wins if duplicate aliases found
_brunner_runMethod "$(dirname "$1")" "$2"
fi
if [ -f "$1/.aliases" ]; then
_brunner_parseAliases "$1/.aliases" "$2"
fi
}
function _brunner_parseAliases() {
# per-directory .brunner file must end with an empty line
while read -r line; do
aliasName=$(echo "$line" | cut -d' ' -f1)
aliasContent=$(echo "$line" | cut -d' ' -f2-)
"$2" "$aliasName" "$aliasContent"
done < "$1"
}
function _brunner_unsetAlias() {
unalias "$1" 2>/dev/null
}
function _brunner_setAlias() {
alias "$1"="$2";
}
function cd() {
_brunner_runMethod "$(pwd)" _brunner_unsetAlias
command cd "$@" || return
_brunner_runMethod "$(pwd)" _brunner_setAlias
}
# so it applies to the first directory when opening a new shell
_brunner_runMethod "$(pwd)" _brunner_setAlias
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment