Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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