3

If we set custom environment variables in .bashrc like the following:

TMP_STRING='tmp string'

It seems like this variable is not directly accessible from the bash script.

#!/bin/bash

echo $TMP_STRING

I tried the following, but it also doesn't work:

#!/bin/bash

source ~/.bashrc

echo $TMP_STRING

Could you suggest what would be the correct way in this case? Thank you!

chanwcom
  • 4,420
  • 8
  • 37
  • 49

1 Answers1

5

Just VAR=value defines a shell variable. Environment variables live in a separate area of process memory that is preserved when another process is started, but are otherwise indistinguishable from shell variables.

To promote a variable to an environment variable, you must export it.

Example:

VAR=value
export VAR

or

export VAR=value

If you put the above into .bashrc, the above value of $VAR should be available in the script, but only if it's run from the login shell.

I would not recommend sourcing .bashrc in the script. Instead, create a separate file named something like .script.init.sh and source that:

# script init
TMP_STRING='tmp string'

Your script:

# script
. ~/.script.init.sh

If this value must be available to any process spawned by the script, prefix it with export :

# script init
export TMP_STRING='tmp string'
Henk Langeveld
  • 8,088
  • 1
  • 43
  • 57