LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash: export variable in current or parent shell (https://www.linuxquestions.org/questions/programming-9/bash-export-variable-in-current-or-parent-shell-4175477147/)

hydraMax 09-14-2013 04:52 PM

bash: export variable in current or parent shell
 
Hi. I'm making bash scripts that are supposed to set environment variables for certain software modules. (E.g., I would run a libXYZ environment script before trying to compile anything with libXYZ.) However, it seems that if I run a bash script (outside of .bashrc or .bash_profile) that the variables are only set for the script itself and children of the script. How do I either 1) get the script commands to run inside the parent shell (instead of a subshell) or 2) get the variables to export up to the parent shell?

If I'm not making sense let me know and I will try to explain more.

firstfire 09-14-2013 05:12 PM

Hi.

To make variables visible in parent shell use source <scriptname> (or . <scriptname>) instead of executing it via ./<scriptname>.

hydraMax 09-14-2013 10:46 PM

Thanks firstfire!

I wanted to mention, for posterity's sake: when using source, all the variable setting commands will affect your shell, not just the export commands. This can cause problems if you weren't expecting it. In short, you can't have "local" variables in top-level of the script you source.

A way around this is to wrap your entire script in a function call, use the local builtin, and call the function. E.g.,

Code:

# script to be sourced

function main()
{
  local foodir=foo # scope limited to function
  export PATH=${HOME}/${foodir} # global scope
}

main

If there is a better way to do that, I'd be glad to know.


All times are GMT -5. The time now is 12:17 PM.