Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable defined in .bashrc from a bash script [duplicate]

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!

like image 664
chanwcom Avatar asked Jun 17 '26 17:06

chanwcom


1 Answers

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'
like image 131
Henk Langeveld Avatar answered Jun 19 '26 13:06

Henk Langeveld