Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I output env as a runnable shell script

Tags:

bash

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='"'"'" ?

like image 367
Sam Saffron Avatar asked Nov 26 '14 00:11

Sam Saffron


People also ask

How do I export a .env variable?

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 ").

How do I print an environment variable in bash?

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.

How do I set an environment variable in shell?

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.


1 Answers

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.

like image 75
Charles Duffy Avatar answered Nov 02 '22 07:11

Charles Duffy