Getting Started
To set environment variables persistently, you normally have to add it to your .bashrc or .profile. However, this can be annoying, and often more trouble than it's worth. An alternative is writing a function in your .bashrc that appends to a global .env file, and sourcing that file in your .bashrc. I'll show the code and then break it down
setenv() {
FILE=$HOME/.env
if [[ ! -f "$FILE" ]]; then
touch $FILE
source $FILE
fi
echo $1=$2 >> $FILE
export $1=$2
}
[ -f $HOME/.env ] && source $HOME/.env
Code Breakdown
The first line of the function sets the file variable to a .env in the user's home directory. The if statement checks if the file doesn't exist, and if it doesn't, then it creates the file and sources it. The echo command appends to the .env file with the first and second arguments. The export command makes the environmental variable available right after running the command.
Finally, the last line sources the file, but only if it exists
Usage
You could then run something like this in your terminal (after reopening it)
setenv WORKING hopefully
This is the general syntax for the command
setenv <key> <value>
Note: If you refine a variable, like this,
setenv WORKING false
setenv WORKING true
the file will include both of these, but the first will be unused.
Wrapping things up
I use many other aliases and functions, but this is one that I recently thought of, and it is very useful.
Thanks for reading 🎉
Top comments (0)