1

Recently I have been asked a question. What are the different ways of executing shell script and what is the difference between each methods ?

I said we can run shell script in the following methods assuming test.sh is the script name,

  1. sh test.sh
  2. ./test.sh
  3. . ./test.sh

I don't know the difference between 1 & 2. But usually in first 2 methods, upon executing, it will spawn new process and run the same. Whereas in the last method, it won't spawn new process. Instead it runs in the same one.

Can someone throw more insight on this and correct me if I am wrong?

4

1 回答 1

9
sh test.sh

Tells the command to use sh to execute test.sh.

./test.sh

Tells the command to execute the script. The interpreter needs to be defined in the first line with something like #!/bin/sh or #!/bin/bash. Note (thanks keltar) that in this case the file test.sh needs to have execution rights for the user performing this command. Otherwise it will not be executed.

In both cases, all variables used will expire after the script is executed.

. ./test.sh

Sources the code. That is, it executes it and whatever executed, variables defined, etc, will persist in the session.

For further information, you can check What is the difference between executing a bash script and sourcing a bash script? very good answer:

The differences are:

  • When you execute the script you are opening a new shell, type the commands in the new shell, copy the output back to your current shell, then close the new shell. Any changes to environment will take effect only in the new shell and will be lost once the new shell is closed.

  • When you source the script you are typing the commands in your current shell. Any changes to the environment will take effect and stay in your current shell.

于 2013-08-20T09:47:06.893 回答