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!
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With