42

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.

1

3 Answers 3

49

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 
    12

    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.

    1
    • 2
      Upvoted for debugging tip.
      – Stephen C
      CommentedJul 28, 2019 at 8:15
    10

    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 
    1
    • 2
      To learn more about sourcing vs executing: link
      – aderchox
      CommentedNov 17, 2021 at 14:16

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.