Skip to content

Instantly share code, notes, and snippets.

@damusix
Last active February 20, 2021 23:57
Show Gist options
  • Save damusix/ba1042a15ea9294ced800d30c8e58390 to your computer and use it in GitHub Desktop.
Save damusix/ba1042a15ea9294ced800d30c8e58390 to your computer and use it in GitHub Desktop.
Zsh based dotenv + add local paths as bash programs
# Set the project's local path to PATH
setlocalpath() {
if [ -f .pathrc ];
then;
localpaths=$(cat .pathrc | xargs)
echo "Setting local path in '.pathrc' ..."
# If pathrc is empty, use cwd
# Otherwise, convert the contents of pathrc
# Into an array and add all to PATH
if test -z $localpaths
then
PATH=$(pwd):$PATH
else
for p (${=localpaths}); do
ADDPATH=$(pwd)/$p
# Make sure path has not been added
# And make sure the directory exists
if [ "${string#*$ADDPATH}" != "$PATH" ] && [ -d $ADDPATH ]
then
PATH=$ADDPATH:$PATH
fi
done
fi
export PATH
fi
}
# Manually set env
setenv() {
[[ -f .env ]] \
&& echo "Exporting variables in '.env'..." \
&& export $(cat .env | grep -v '^\#' | xargs);
}
# Function to run after changing directories
afterCdFn() {
setenv;
setlocalpath;
# Automatically set node version if nvmrc exists
[[ -f .nvmrc ]] \
&& nvm use
}
# Gracefully overwrite `cd` function
# https://stackoverflow.com/questions/3360738/execute-a-bash-function-upon-entering-a-directory
function cd () { builtin cd "$@" && afterCdFn; }
# Automatically source .env files on new zsh session
setenv;
setlocalpath;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment