Skip to content

Instantly share code, notes, and snippets.

@subfission
Created March 11, 2024 19:21
Show Gist options
  • Save subfission/5a66680b9ea4354dd32a45aa999f950b to your computer and use it in GitHub Desktop.
Save subfission/5a66680b9ea4354dd32a45aa999f950b to your computer and use it in GitHub Desktop.
Best way to source a file or directory after null checking
#
# Example ternary to source a directory into PATH if it exists
#
[ -d $HOME/custom/dir ] && export PATH=$PATH:${HOME}/custom/dir
#
# Better way to source a path into the global environment through function calls
#
add_to_path() { [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]] && export PATH="$1:$PATH"; }
#
# Better way to source a bash config
#
resource() { [ -f "$1" ] && source "$1"; }
@subfission
Copy link
Author

Finish with:

unset -f add_to_path resource

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment