Programming
shell scripting environment-variables
Updated Fri, 20 May 2022 22:19:08 GMT

Global environment variables in a shell script


How to set a global environment variable in a bash script?

If I do stuff like

#!/bin/bash
FOO=bar

...or

#!/bin/bash
export FOO=bar

...the vars seem to stay in the local context, whereas I'd like to keep using them after the script has finished executing.




Solution

Run your script with .

. myscript.sh

This will run the script in the current shell environment.

export governs which variables will be available to new processes, so if you say

FOO=1
export BAR=2
./runScript.sh

then $BAR will be available in the environment of runScript.sh, but $FOO will not.





Comments (4)

  • +0 – Be careful with that first one. Without a slash, it will look in your path: use something like '. ./myscript.sh' if you want to ensure it runs a specific one. — Sep 23, 2009 at 06:47  
  • +0source is an alias for .. So you could run source myscript.sh instead, if you wanted to be more explicit. — Jul 01, 2013 at 17:14  
  • +0 – I am wondering what happens when i run a script with dot and a space. example . myscript — Sep 09, 2019 at 20:23  
  • +0 – @cNgamba Ask a new question if you can't find it by reading the other answers on this page and/or googling, but this is a common FAQ; see also e.g. unix.stackexchange.com/questions/114300/… — Mar 01, 2021 at 19:16