Bash Scripting

Running a Script

To run a non-executable sh script, use:

sh myscript

To make a script executable, give it the necessary permission:

		
		chmod +x myscript 
		./myscript 
		

How Unix run a script

When a file is executable, the kernel is responsible for figuring out how to execute it.

For non-binaries, this is done by looking at the first line of the file.

It should contain a hashbang:

#! /usr/bin/env bash
shebang

In computing, a shebang (also called a hashbang) is the character sequence consisting of the characters number sign and exclamation point (#!), when it occurs as the first two characters on the first line of a text file.

In this case, the program loader in Unix-like operating systems parses the rest of the first line as an interpreter directive and invokes the program specified after the character sequence with any command line options specified as parameters.

The name of the file being executed is passed as the final argument

The hashbang tells the kernel what program to run (in this case the command /usr/bin/env is ran with the argument bash).

Then, the script is passed to the program (as second argument) along with all the arguments you gave the script as subsequent arguments.

That means every script that is executable should have a hashbang.

If it doesn't, you're not telling the kernel what it is, and therefore the kernel doesn't know what program to use to interprete it. It could be bash, perl, python, sh, or something else. (In reality, the kernel will often use the user's default shell to interprete the file, which is very dangerous because it might not be the right interpreter at all or it might be able to parse some of it but with subtle behavioural differences such as is the case between sh and bash.)