Tuesday, March 15, 2011

Multiple ways to execute any shell script

Different ways of executing shell script mainly falls under two categories.
1. Executing the shell script in a new shell
2. Executing the shell script in the current shell

1.How to execute the shell script in a new shell.
This type can be accomplished in two ways. But any changes made to the shell or its environment will not be retained after the script execution.

a) Script set with execute permission and then executed in a new shell
As a general standard UNIX practice, we should set execute permission for any script before proceeding with execution.

Example:
volcano@volcano-laptop:~/shellscript$ chmod u+x hello.sh
volcano@volcano-laptop:~/shellscript$ ./hello.sh
Hello World!

b) Execution of script without setting execute permission for the script
We can achieve it by passing the script name as an argument to the shell. In the below example, if you keenly observe the permission of the owner of the file was not set.

Example:
volcano@volcano-laptop:~/shellscript$ ls -l hello.sh
-rw-r--r-- 1 volcano volcano 56 2011-03-13 00:41 hello.sh
volcano@volcano-laptop:~/shellscript$ bash hello.sh
Hello World!

 2. Executing the shell script in the current shell
Bash supports . (dot) & source command to make this possible. But any changes made to the shell or its environment will be in effect after the script execution.


Example:
volcano@volcano-laptop:~/shellscript$ . ./hello.sh
Hello World!
volcano@volcano-laptop:~/shellscript$ source ./hello.sh
Hello World!

Note: For running the script in the current shell also there is no need for to set the file with execute permission.

Why always ./ is used in front of the script for execution in all our examples will be detailed in the next post.

No comments:

Post a Comment