88

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
joeytwiddle
  • 29,306
  • 13
  • 121
  • 110
user408041
  • 1,064
  • 1
  • 8
  • 12

2 Answers2

150

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.

MangeshBiradar
  • 3,820
  • 1
  • 23
  • 41
  • 5
    `.` is an alias for `source` when delimited by space (like all bash commands). If you `source` you'll avoid common bugs associated with using `.` to mean the current directory, etc. – hobs Mar 20 '18 at 00:58
  • 15
    Note: `source` is an alias for `.` not the other way around. – Douwe van der Leest Aug 27 '18 at 12:28
  • 1
    This works fine for scripts in the current directory - but what do you do if the script is in /usr/local/bin? That's more convenient because then you don't have to cd to the directory where your script is located. – henrikstroem Feb 08 '20 at 12:34
12

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
clusterdude
  • 616
  • 3
  • 16
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • If I use ./source.sh it does not work. source source.sh does work! – user408041 Apr 15 '13 at 10:07
  • 1
    SInce you're providing full path to setup.sh here therefore `./` is not needed since `./` means current dir. – anubhava Apr 15 '13 at 11:01
  • 4
    "`./source.sh`" executes the script (in its own shell). "`. ./source.sh`" (or "`source ./source.sh`", or "`source source.sh`") will apply the script contents to the current shell environment. – clusterdude Mar 13 '17 at 17:58