Setting environment variables from ordinary bash script is rarely used and that is why this behavior may be for someone surprising.
Print your environment variables
Environment variables can be set for:
- Current bash process and sub-processes
SystemInteractive login shell first reads and executes commands from the file /etc/profile, if that file exists.
Some Linux systems now use a directory /etc/profile.d/; any .sh files in there will be sourced by /etc/profile.
UserAfter reading /etc/profile, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable.
Process and subprocesses$ export DB_URL=mongodb://localhost:27017/testaBD
It affect current bash process and subprocesses.
When you export variables in a bash script:
- It opens a new shell.
- It executes commands.
- It copies the output back to your current shell.
- It closes the new shell.
Any changes to environment will take effect only in the new shell and will be lost once the new shell is closed.
It's important to note that exporting a variable doesn't make it available to parent process. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.
Source a bash script
$ source script.sh
Sourcing the script does not create a new shell. All commands are run in the current shell and changes to the environment take effect in the current shell. When you source the script you are typing the commands in your current shell. Any changes to the environment will take effect and stay in your current shell.