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,<ol><li>sh test.sh </li> <li>./test.sh</li> <li>. ./test.sh</li> </ol>
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?Answer1:
Tells the command to use
sh to execute
Tells the command to execute the script. The interpreter needs to be defined in the first line with something like
#!/bin/bash. Note (<a href="https://stackoverflow.com/questions/18331893/difference-between-different-ways-of-running-shell-script/18331933?noredirect=1#comment26906428_18331933" rel="nofollow">thanks keltar</a>) 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.
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 <a href="https://superuser.com/questions/176783/what-is-the-difference-between-executing-a-bash-script-and-sourcing-a-bash-scrip" rel="nofollow">What is the difference between executing a bash script and sourcing a bash script?</a> very good answer:<blockquote>
The differences are:<ul><li>
When you <em>execute</em> the script you are opening a <em>new</em> 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.</li> <li>
When you <em>source</em> the script you are typing the commands in your <em>current</em> shell. Any changes to the environment will take effect and stay in your current shell.</li> </ul></blockquote>