Executing or run a Shell Script in UNIX or Linux

Method 1

Execute Shell Script by Specifying the Interpreter

You can also execute a unix shell script by specifying the interpreter in the command line as shown below.

 Execute using sh interpreter

 $ sh  scriptfilename

Execute using bash interpreter

$ bash  scriptfilename
 Irrespective of what is being used as shebang, the interpreter which you have specified will be used for execution. You can use any interpreter (sh, ksh, bash, csh etc.,).
( This is best way to run shell script )


Method 2 

  Execute Shell Script Using File Name

Use the shell script file name to execute it either by using it’s relative path or absolute path as shown below.

$ cd /home/sathiya
$ ./scriptfile

(or)

$ /home/sathiya/scriptfile

If you have the shebang, then it will be executed using the command interpreter specified in the shebang

 

Method 3

 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.
$ . ./scriptfile
In other words, this executes the commands specified in the scriptfile in the current shell, and prepares the environment for you.

“dot space dot slash” Usage Example:

Typically we use this method, anytime we change something in the .bashrc or .bash_profile. i.e After changing the .bashrc or .bash_profile we can either logout and login for the changes to take place (or) use “dot space dot slash” to execute .bashrc or .bash_profile for the changes to take effect without logout and login.
$ cd ~

$ . ./.bashrc

$ . ./.bash_profile

 

Method 4

Execute Shell Script Using Source Command

The builtin source command is synonym for the . (dot) explained above. If you are not comfortable with the “dot space dot slash” method, then you can use source command as shown below, as both are same.


$ source ~/.bashrc


No comments

Powered by Blogger.