Monday, April 9, 2012

What is sourcing a file?



   UNIX users would have heard the term "sourcing a file" pretty frequently. What exactly do we mean by sourcing a file? Which files do we source? What is the use of it? Let us see in this article about this in detail.

1. What is sourcing a file? 
  Sourcing a file is nothing but executing the file, more importantly making the changes of the file applicable in the current shell itself, the shell which we are working in. Usually, when we execute a command or a script, a new sub-shell is created and the script is executed in the sub-shell. Due to this, if the script or the command intends to make any change to the current shell, it will not happen. In order to make the changes applicable in the current shell itself, we "source" the file.

 Let us take an example to understand this by writing a script to change the current directory to temp.
$ cat a.sh
#!/usr/bin/bash

cd temp
Check the current directory before running the script:
$ pwd
/home/guru
Let us run the script:
$ ./a.sh
/home/guru/temp
After running the script,  the current directory is:
$ pwd
/home/guru
  As seen above, it is clear that the command is indeed executed in a sub-shell, not in the main shell itself. That is the reason why the change is effected in the sub-shell, and not in the shell from which the script is invoked. In fact, we could have also proved this by checking the process id of the shell script which should have been different from the process id of our home shell.

  To make this change permanent in our current shell is what we use the source command for:
$ source a.sh
Now, let us check the current directory after sourcing the script:
$ pwd
/home/guru/temp
      This is the meaning of sourcing of a file.

 2What is the difference between the sourcing and executing of a file?
     The difference between sourcing and executing a file is : executing a file does not make any changes in the current shell, if intended, whereas the sourced file makes the changes in the current shell itself.
   Usually, the alias and profile files are the ones which are sourced since they contain stuffs like setting of environment variables , aliases definition, etc. In the same way as above, we execute the alias and profile files:
To execute or run .alias file:
$ source $HOME/.alias
To execute the profile file:
$ source $HOME/.profile
3. Is the source command effective across all shells?
   No. Only in Korn-Shell(KSH), you have to use the dot(.) command which is korn variant of source. Majority of the shells use the source command to source a file. This is the only difference between the source and dot(.) command. The syntax is: 
. <file>  #dot followed by filename

For example, to execute the .alias file in Ksh:
$ . $HOME/.alias
To execute the .profile file or any other profile file in ksh:
$ . $HOME/.profile

3 comments: