Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source files in a bash script

Tags:

bash

shell

ubuntu

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 
like image 526
user408041 Avatar asked Apr 15 '13 08:04

user408041


People also ask

Can I use source in a shell script?

source is a shell built-in command which is used to read and execute the content of a file(generally set of commands), passed as an argument in the current shell script. The command after taking the content of the specified files passes it to the TCL interpreter as a text script which then gets executed.

How do you source a file in shell?

A file is sourced in two ways. One is either writting as source <fileName> or other is writting as . ./<filename> in the command line. When a file is sourced, the code lines are executed as if they were printed on the command line.

What does source in bash do?

The source command reads and executes commands from the file specified as its argument in the current shell environment. It is useful to load functions, variables, and configuration files into shell scripts. source is a shell built-in in Bash and other popular shells used in Linux and UNIX operating systems.


2 Answers

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.

like image 60
MangeshBiradar Avatar answered Sep 21 '22 23:09

MangeshBiradar


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 
like image 26
anubhava Avatar answered Sep 22 '22 23:09

anubhava