feat: add environment file helper functions

master
Kebler Network System Administrator 2022-12-24 12:34:03 -08:00
parent 3e8be4da72
commit 4318f9ca89
2 changed files with 63 additions and 3 deletions

View File

@ -115,10 +115,10 @@ module_loaded() {
# function_list | grep module
file=$(module_find $1)
[ ! $file ] && echo no module $1 found && return 1
# echo "$(function_list $file)"
# echo list "$(function_list $file)"
for func in $(function_list $file)
do
[ ! $(function_list | grep $func) ] && ret=1
do
[[ ! $(function_list | grep $func) ]] && ret=1
[[ $2 = -vv ]] && ([[ $ret = 0 ]] && echo "$func loaded" || echo "$func not loaded")
done
[[ $2 = -v ]] && echo "module: $1" && ([[ $ret = 0 ]] && echo "all functions " || echo "some or all functions not loaded")

View File

@ -12,6 +12,10 @@ is_array() {
[[ "$(declare -p $variable_name 2>/dev/null)" =~ "declare -a" ]]
}
is_function() {
[[ $(type $1 2> /dev/null) ]] && echo $1 is a function
}
filename() {
# passed entire path
echo $(basename "$1" | rev | cut -f 2- -d '.' | rev)
@ -60,3 +64,59 @@ remove_end_spaces () {
sed -e "s/[[:space:]]*${del}$/$del/" <<< "$res"
}
# pass any sed ' ' string and command lines will be ignored
# https://unix.stackexchange.com/a/301432/201387
# https://stackoverflow.com/a/35874420/4695378
sed_ignore_comments () {
cmd="sed -r 'h;s/[^#]*//1;x;s/#.*//;${1};G;s/(.*)\n/\1/'"
if (( $# == 2 )) ; then
eval $cmd <<< "$2"
else
eval $cmd < /dev/stdin
fi
}
# https://stackoverflow.com/questions/19331497/set-environment-variables-from-file-of-key-value-pairs
env_file () {
env=${1:-.env}
[[ -f "${env}" ]] && { echo $env; return 0; } # || echo not $env
[[ -f "${env}.env" ]] && { echo "${env}.env"; return 0; } # || echo not ${env}.env
[[ -f "${env}/.env" ]] && { echo "${env}/.env"; return 0; } # || echo not ${env}/.env
return 1
}
# ignore non assignment lines
list_env_file_vars () {
env=$(env_file $1)
[[ ! $env ]] && { iecho "Env file ${1} doesn't exist"; return 1; }
echo $(grep -v '^#' ${env} | sed -n -E 's/(.*)=[^ =].*/\1/p' | xargs)
}
list_env_file_vals() {
vars=$(list_env_file_vars $1)
[[ $? -gt 0 ]] && return 1
for var in $(list_env_file_vars $1) ;
do
echo "$var=${!var}"
done
}
source_env_file() {
env=$(env_file $1)
[[ ! $env ]] && { iecho "Env file ${1} doesn't exist"; return 1; }
source $env
}
export_env_file () {
env=$(env_file $1)
[[ ! $env ]] && { iecho "Env file ${1} doesn't exist"; return 1; }
set -a; source $env; set +a
}
unset_env_file () {
env=$(env_file $1)
[[ ! $env ]] && { iecho "Env file ${1} doesn't exist"; return 1; }
unset $(grep -v '^#' ${env} | sed -E 's/(.*)=.*/\1/' | xargs)
}