1

I have the following script named export.sh:

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done

SOURCE=$(dirname ${SOURCE})

export $(cat "${SOURCE}/../params.env" | xargs)

In some words what it does it to export enviromental variables from a file named params.env that is located by convention on the prarent folder and exports the contents as enviromental variables.

Sample contents of params.env file are:

SOMEVAR="val1"
SOMEVAR2="val2"

And a successfull run will provide me SOMEVAR with value val1 and SOMEVAR2 with value val2 enviromental variables.

But if I run:

./export.sh

And afterwards

printenv | grep SOMEVAR

It does not show that the enviromental variable is set.

marked as duplicate by muru, Satō Katsura, Community Oct 20 '17 at 8:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

The entire idea is right, but you you end up executing the shell script rather than sourcing it to make the environment changes in the current shell.

Remember always, executing a script runs a sub-shell and all the exported system environment variables are lost after the sub-shell is terminated.

See what happens when you run the script is executed, with the debug mode set -x (FYI, am using params.env from the current folder)

$ bash -x script.sh
+ SOURCE=script.sh
+ '[' -h script.sh ']'
++ dirname script.sh
+ SOURCE=.
++ cat ./params.env
++ xargs
+ export SOMEVAR=val1 SOMEVAR2=val2
+ SOMEVAR=val1
+ SOMEVAR2=val2

You can see the variables are set but the sub-shell destroys the variables exported. Now on sourcing the script,

source script.sh
printenv | grep SOMEVAR
SOMEVAR=val1
SOMEVAR2=val2

If your bash version does not support an explicit source command, use the POSIX compliant ways of doing . ./script.sh

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