您的位置:首页 > 运维架构 > Shell

4 Ways of Executing a Shell Script in UNIX / Linux

2014-03-20 20:00 651 查看
There are four ways to execute a shell script. Each way has it’s own meaning as explained in this article.

1. 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. If you are beginner in shell scripting, refer our earlier article
Shell Script Execution Guidelines for Newbies

2. 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 scriptfile

Execute using bash interpreter

$ bash scriptfile

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.,).

3. Execute Shell Script Using .  ./ (dot space dot slash)

only . (dot) means execute given command file in current shell without starting the new copy of shell
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 script file 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 takeplace (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

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

Which method do you prefer to execute a shell script?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell linux linux shell