DEV Community

alelee93
alelee93

Posted on

The Shebang #!

Lets assume you have a Ruby file ./program with the following line of code:

puts 'hello world'

If you run ./program in your terminal, your computer would be agnostic to what type of program you are trying to run. For your computer ./program might be a Bash script, Perl, Python, or an actual binary executable. This is when shebangs become relevant.

For the terminal, the shebang acts as a hint on how to execute a file if you don't explicitly tell your computer what to use to execute such file. For example, if you run ruby ./program, you are explicitly telling your computer to use ruby to run your program, but if you simply run ./program, your computer would know to use ruby as the interpreter if your program includes a shebang.

Tip: Note that having a shebang at the beginning of your file would not affect the program itself.

So what is a shebang?!

This character sequence is called a shebang:

#!

and it is used to tell a Unix-like operating system (such as OS X or Linux) which interpreter to use to parse or execute a file.

A #! (shebang) is followed by an interpreter directive path, which specifies the program to be run.

See below the structure of a shebang interpreter directive:

#![path to your interpreter directive] argument`

Note that your shebang interpreter directive should be the first line of your script.

There are 2 ways to use the shebang directive and set the interpreter:
1) Using the absolute path
2) Using the env directive

Here is an example using an absolute path:

#!usr/bin/python

In this example, your computer would execute the file using python.

Here is an example using the env directive:

#!/usr/bin/env ruby

In this example the env command would locate the path to the ruby interpreter by itself, whether it is located in the /usr/bin/directory, or somewhere else, you would not need to find the absolute path by yourself, instead the env program would figure it out at runtime.

Tip: Using the env command makes your program more portable.

Top comments (0)