You can trivially output your environment as a runnable shell script using
env > my_env
... later in another script ...
set -a
source my_env
This works for the most trivial cases, but fails if any special chars or spaces are in env.
How can I fix the above script so it works with stuff like a='"'"'"
?
To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").
The “printenv” command displays the currently active environment variables and the previously specified environment variables in the shell. You can see the output of using the “printenv” command to display all the environment variables in the shell as per the snapshot below.
You can set your own variables at the command line per session, or make them permanent by placing them into the ~/. bashrc file, ~/. profile , or whichever startup file you use for your default shell. On the command line, enter your environment variable and its value as you did earlier when changing the PATH variable.
The following uses bash's printf %q
to escape values correctly regardless of their content. It's guaranteed to handle literally any value possible -- quotes, newlines, etc -- so long as the shell sourcing its output is bash, and so long as the operating system in use supports the /proc/self/environ
facility first provided by Linux to emit the contents of the environment as a NUL-delimited stream. It uses special quoting forms such as $'\n'
as and where appropriate, so its output may not be honored by pure POSIX interpreters.
#!/usr/bin/env bash
while IFS= read -r -d '' kvname; do
k=${kvname%%=*}
v=${kvname#*=}
printf '%q=%q\n' "$k" "$v"
done </proc/self/environ
Note that you'll want to source the output, not run it as an external executable, if you want your current shell's environment to change. If you don't want to set -a
before sourcing, add a leading export
to the format string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With