import environment variables in a bash script

91,448

Solution 1

If the variables are truly environment variables (i.e., they've been exported with export) in the environment that invokes your script, then they would be available in your script. That they aren't suggests that you haven't exported them, or that you run the script from an environment where they simply don't exist even as shell variables.

Example:

$ cat script.sh
#!/bin/sh

echo "$hello"
$ sh script.sh

(one empty line of output since hello doesn't exist anywhere)

$ hello="hi there"
$ sh script.sh

(still only an empty line as output as hello is only a shell variable, not an environment variable)

$ export hello
$ sh script.sh
hi there

Alternatively, to set the environment variable just for this script and not in the calling environment:

$ hello="sorry, I'm busy" sh script.sh
sorry, I'm busy
$ env hello="this works too" sh script.sh
this works too

Solution 2

You need to ensure you export the environment variables you want to have access to in your script before you invoke the script. IE:

Unix> export MY_TEMP=/tmp
Unix> some_script.sh

Now some_script.sh would have access to $MY_TEMP -- when you invoke a shell script, you get a new environment, with only exported variables, unless you "source" it by preceeding the script command with a period (".") and a space, then your script name:

Unix>  . some_script.sh  # runs in current environment

Debugging tip: Include near the top of your script the set command to see what variables your script can see.

Solution 3

Also note that if you want them to only live for "the duration of the execution of the script", you can put the exports of them in a file and then source that file within your script.

Because when you execute a script, it will be executed in a new shell, this way those variables will be exported in that subshell (and its descendants) only and they will not end up in your own shell, i.e., it will look as if you unset them automatically after the end of the execution of the script.

Example:

# config.txt
export SECRET=foobar
# prog.sh
#!/usr/bin/env sh
source ./config.txt
echo $SECRET

Now run it:

chmod +x prog.sh
./prog.sh

and then confirm that the SECRET variable has not leaked into your own shell:

echo $SECRET # <-- must echo a blank line
Share:
91,448
Mark
Author by

Mark

Updated on September 18, 2022

Comments

  • Mark
    Mark over 1 year

    I set some environment variables in a terminal, and then run my script. How can I pull in the variables in the script? I need to know their values. Simply referring to them as $MY_VAR1 doesn't work; it is empty.

  • jakob-wenzel
    jakob-wenzel over 4 years
    Upvoted for debugging tip.
  • aderchox
    aderchox over 2 years
    To learn more about sourcing vs executing: link