Four ways to execute a shell script

shebang script explainedIf you need to execute a shell script and can’t get your head around the conflicting information out there, I’ll try to clear things up. There are quite a few ways to execute a shell script and each has its pros and cons. If you are coming from a Windows environment where the file extension dictates how we handle the file, then try not to think like this. A script can have no extension but still be run. So, let’s take a look at our four ways to execute a shell script.

 

Execute shell script by calling the filename (Method 1)

This method simply changes into the script’s containing directory and calls the script’s file name to execute it.

We can change into the directory first

$ cd /usr/bin

 

and then call the script thus:

$ ./myscript

 

Now, my preferred method is to consolidate these 2 lines into 1 , calling it from any directory by simply adding the full path to the file:

$ /usr/bin/myscript

 

If you have the shebang at the start of this script, then it will be executed by using the command interpreter that is specified directly after it.

Execute shell script by specifying an interpreter (Method 2)

You can also run a shell script by specifying the interpreter. You do this by adding the preferred interpreter within the command thus:

Execute the script using the bash interpreter

$ bash myscript

 

Execute the script using the sh interpreter

$ sh myscript

 

There are usually several interpreters available such as bash, sh,  csh, ksh and more.  Note that if you use a different interpreter in the shebang, this will be overridden by the one you specify.

Execute shell script with . ./ (Method 3)

If you execute the shell script by using . ./ (aka ‘dot space dot slash’), it will not fork a sub shell and you’ll see it executed in the current shell.

$ . ./myscript

 

Why do this? Well it’s normally used after we have changed something in the .bashrc or .bash_profile. Using this method of execution we won’t need to logout and login again.

$ cd ~

$ . ./.bashrc

$ . ./.bash_profile

Execute shell script with source command (Method 4)

source is a bash shell built-in command that executes the contents of the file, which is passed as argument, in the current shell. It has a synonym that you can use which is the dot or period (.)

This can replace the ‘dot space dot slash’ method.

source myscript [arguments]

. myscript [arguments]

 

A word of warning here though because ./ and source are not quite the same.

./myscript runs myscript as an executable file in a new shell
source myscript reads and executes commands in the current shell environment

To help further, ./myscript is not the same as . myscript, but . myscript is exactly the same as source myscript

 

Do you have a preferred method for executing shell scripts and if so, why? Let me know below.

Leave a Reply

Your email address will not be published. Required fields are marked *