Source files in a bash script

BashShellUbuntu

Bash Problem Overview


I am using two versions of ROS next to each other. To use one I have to source some environment variables for the specific version. I would like to create a script that does this. But if I create a script like below the variables are not set, they are probably set in a subshell. How can I source the files to the main terminal shell?

source.sh:

source /opt/ros/fuerte/setup.bash;
source  ~/fuerte_workspace/setup.bash;

Here is how i am calling source.sh:

./source.sh
# This does not echo anything, but I expect it should
echo $ros_config

Update: By sourcing source.sh as suggested in the answer, I can now see the variables being set.

source ./source.sh
# This works now
echo $ros_config

Bash Solutions


Solution 1 - Bash

Execute Shell Script Using . ./ (dot space dot slash)

While executing the shell script using “dot space dot slash”, as shown below, it will execute the script in the current shell without forking a sub shell.

$ . ./setup.bash

In other words, this executes the commands specified in the setup.bash in the current shell, and prepares the environment for you.

Solution 2 - Bash

Use dot notation to source in the script file in the current shell i.e. without creating a sub-shell:

. /opt/ros/fuerte/setup.bash
. ~/fuerte_workspace/setup.bash

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser408041View Question on Stackoverflow
Solution 1 - BashMangeshBiradarView Answer on Stackoverflow
Solution 2 - BashanubhavaView Answer on Stackoverflow