Skip to content

Instantly share code, notes, and snippets.

@blizzrdof77
Created September 15, 2020 23:03
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save blizzrdof77/4f808949037cbb69460763a638be4aec to your computer and use it in GitHub Desktop.
Save blizzrdof77/4f808949037cbb69460763a638be4aec to your computer and use it in GitHub Desktop.
Create new environment variable & print assignment statement to your shell's '.rc' file
# -----------------------------------------
# Create new environment variable & print assignment statement to your shell's '.rc' file
#
# @1 = variable new
# @2 = variable definition
# @requires: '~/.zshrc' or '~/.bashrc'
# -----------------------------------------
function new_env_var {
local detected_shell="$(ps -o comm= -p $$)"
local rcfile=$(echo "${HOME}/.${detected_shell//-/}rc")
if [[ -f $rcfile ]]; then
local var_name; local var_val
if [ -z "$1" ]; then
echo "variable name (e.g. 'NEW_VAR' for '\$NEW_VAR'):"; read var_name
else
var_name=$1
fi
if [ -z "$2" ]; then
echo "variable definition:"; read var_val
else
local s2 var_val="${@//${var_name}/}"
until s2="${var_val#[ ]}"; [ "$s2" = "$var_val" ]; do var_val="$s2"; done
fi
echo "export $var_name=\"$var_val\"" >> $rcfile; export $var_name="$var_val"
else
echo "No $detected_shell runcom file found. Please make sure $rcfile exists."
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment