difference between source, exec and ./script

What is the difference between sourcing a script, running it or execing it?

./script creates a new shell and executes each command in the script within the new shell. When the end of the script file is encountered, the new shell exits. Any changes in the new shell caused by the script are lost when the shell exits.

For example, if the file
/home/user/sample/script/test contains...

cd /usr/games
pwd
echo hi

Then the command sequence would yield the following output:

prompt>cd /home/user/sample/script
prompt>pwd
/home/user/sample/script
prompt>chmod +x test
prompt>./test
/usr/games
hi
prompt>pwd
/home/user/sample/script

source Execution
source execute a shell script within the context of the current shell. Since execution takes place within the context of the current shell, any changes in the shell are retained following the completion of the shell.
Example:

prompt>cd /home/user/sample/script
prompt>pwd
/home/user/sample/script
prompt>source test
/usr/games
hi
prompt>pwd
/usr/games

Execing a <command> (ie. shell script or executable) means give exec <command> on the shell prompt.

The exec command will execute a command in place of the current shell, that is, it terminates the current shell and starts a new process in its place.

exec was often used to execute the last command of a shell script. This would kill the shell slightly earlier; otherwise, the shell would wait until the last command was finished. This practice saves a process and some memory.

try exec ls. you will be logged out from your login shell.

exec also manipulates file descriptors in the Bourne shell.
$exec >>logoutput
after issuing this command you will not see output of any command in your console. all output goes into logoutput file.

use exec >/dev/console to return.

$exec 2>errs.out
means that from then on, stderr goes into errs.out file

hope this will help you

[Edited by mib on 04-15-2001 at 12:14 PM]

2 Likes