Avoid hard-coding the path to the interpreter in your scripts

In general when trying to write portable scripts don’t start them with

#!/bin/bash

, instead start them with

#!/usr/bin/env bash

. The only caveat is that you DO NOT want to do this for critical security scripts because it opens you up to path based exploits.

Scripts are often written with the path to the interpreter hard-coded such as

#!/usr/local/bin/perl

,

#!/usr/bin/bash

, or

#!/usr/local/bin/ruby

which is not very portable. For example on Debian Linux it’s

/bin/bash

whereas on FreeBSD you might find it in

/usr/local/bin/bash

(thanks for the correction Kurin). With Ruby, Perl, and Python it varies even more from sysem to system so we really need a way to start the interpreter from anywhere in your path. Enter env!

In almost all Unix inspired systems you’ll find the env command at /usr/bin/env which uses the path to find the interpreter so if you’re writing scripts to run across systems you’ll greatly improve portability by using

#!/usr/bin/env bash

or

#!/usr/bin/env ruby

.

This entry was posted in Ruby, Systems Administration. Bookmark the permalink.

4 Responses to Avoid hard-coding the path to the interpreter in your scripts