80

I have a tmp.txt file containing variables to be exported, for example:

a=123
b="hello world"
c="one more variable"

How can I export all these variables using the export command, so that they can later be used by child processes?

65
source tmp.txt
export a b c
./child ...

Judging by your other question, you don't want to hardcode the variable names:

source tmp.txt
export $(cut -d= -f1 tmp.txt)

test it:

$ source tmp.txt
$ echo "$a $b $c"
123 hello world one more variable
$ perl -E 'say "@ENV{qw(a b c)}"'

$ export $(cut -d= -f1 tmp.txt)
$ perl -E 'say "@ENV{qw(a b c)}"'
123 hello world one more variable
  • 2
    This won't work if the environment file contains comments, for example. (eg. files that can be reused by systemd's EnvironmentFile) – Chris Lamb Nov 12 '17 at 22:36
  • 3
    @ChrisLamb you can use grep to skip comments: export $(grep --regexp ^[A-Z] tmp.txt | cut -d= -f1) – gvee Jul 2 '18 at 16:05
182
set -a
. ./tmp.txt
set +a

set -a causes variables¹ defined from now on to be automatically exported. It's available in any Bourne-like shell. . is the standard and Bourne name for the source command so I prefer it for portability (source comes from csh and is now available in most modern Bourne-like shells including bash though (sometimes with a slightly different behaviour)).

In POSIX shells, you can also use set -o allexport as a more descriptive alternative way to write it (set +o allexport to unset).


¹ In bash, beware that it also causes all functions declared while allexport is on to be exported to the environment (as BASH_FUNC_myfunction%% environment variables that are then imported by all bash shells run in that environment, even when running as sh).

1

Just do:

while read LINE; do export "$LINE"; done < ./tmp.txt
  • Did you check whether that works? – RalfFriedl Jul 1 at 20:33
  • @RalfFriedl this should work, why not? It's not very elegant and sourcing with set -a would be far simpler, but this does actually work. – terdon Jul 2 at 8:15
  • This is brittle. It does not allow comments in the input file, does not handle quoted variable values properly, and fails on multi-line variables. Granted I don't have many multi-line variables, but I do use comments regularly and often need to use quotes for variable values. – Louis Jul 24 at 15:53
  • It worked for me. – mchawre Aug 7 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.