How to export variables that are set, all at once?

Run the following command, before setting the variables:

set -a 

man page :

-a
When this option is on, the export attribute shall be set for each variable to which an assignment is performed;

To turn this option off, run set +a afterwards.

Example:

set -a
. ./environment
set +a

Where environment contains:

FOO=BAR
BAS='quote when using spaces'

This works if your shell is bash ( possibly other shells as well )

export > /my/env/var/file

your new file will contain a dump of all currently defined variables ... with entries like

declare -x PORT="9000"
declare -x PORT_ADMIN="3001"
declare -x PORT_DOCKER_REGISTRY="5000"
declare -x PORT_ENDUSER="3000"
declare -x PRE_BUILD_DIR="/cryptdata6/var/log/tmp/khufu01/loud_deploy/curr/loud-build/hygge"
declare -x PROJECT_ID="hygge"
declare -x PROJECT_ID_BUSHIDO="bushido"

then to jack up current shell with all those env vars issue

source  /my/env/var/file

`echo "export" $((set -o posix ; set)|awk -F "=" 'BEGIN{ORS=" "}1 $1~/[a-zA-Z_][a-zA-Z0-9_]*/ {print $1}')`
  1. First, get all set environment variables: (set -o posix ; set) Reference: https://superuser.com/questions/420295/how-do-i-see-a-list-of-all-currently-defined-environment-variables-in-a-linux-ba

  2. Get all environment variable names, separated by space: awk -F "=" 'BEGIN{ORS=" "}1 $1~/[a-zA-Z_][a-zA-Z0-9_]*/ {print $1}' Reference: awk-Printing column value without new line and adding comma and https://stackoverflow.com/questions/14212993/regular-expression-to-match-a-pattern-inside-awk-command

  3. Now, we need to export these variables, but xargs can not do this because it forks child process, export have to be run under current process. echo "export" ... build a command we want, then use `` to run it. That's all :p.

Tags:

Bash