Ever opened a file and found
#!/bin/sh or something similar at the top? That’s
a shebang aka hashbang (they go by many names). When the program loader sees a
shebang it will run the program and pass the rest of the file in as the first
Shebangs let you set a command to run before running the rest of the file
The save you having to declare how to run a file. For example: Say you have a
Ruby file named
foobar.rb, to run that file using the Ruby interpretor you’d
need to run
ruby foobar.rb in your terminal.
puts "Hello World!" # To run this file you'll need to use `ruby foobar.md`
But by adding a shebang at the top we can run it without having to tell Linux to use Ruby.
#!/home/path-to-ruby/ruby puts "Hello World!" # To run this file you can simply use `foobar.md`
If your file has a hashbang but you want to run it with an alternative program then you can run it in the usual way and the hashbang will be ignored. This works because many programs will consider the hash to be a comment
Note how in the example above we had to use
#!/home/path-to-ruby/ruby and not
#!ruby. This has an impact on portability because on a different machine
ruby might be in a different path.