2

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.

7

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
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.

  • 1
    Upvoted for debugging tip. – Stephen C Jul 28 at 8:15

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.