3

If we set custom 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!

1
  • 1
    Please explain what you mean with "doesn't work". What do you expect? What actually happens? Commented Apr 1, 2018 at 12:18

1 Answer 1

6

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'
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.