Setting a Secure $PATH

Problem

You want to make sure you are using a secure path.

Solution

Set $PATH to a known good state at the beginning of every script:

# Set a sane/secure path
PATH='/usr/local/bin:/bin:/usr/bin'
# It's almost certainly already marked for export, but make sure
export PATH

Or use the getconf utility to get a path guaranteed by POSIX to find all of the standard utilities:

export PATH=$(getconf PATH)

Discussion

There are two portability problems with the example above. First, `` is more portable (but less readable) than $(). Second, having the export command on the same line as the variable assignment won’t always work. var='foo'; export var is more portable than export var='foo'. Also note that the export command need only be used once to flag a variable to be exported to child processes.

If you don’t use getconf, our example is a good default path for starters, though you may need to adjust it for your particular environment or needs. You might also use the less portable version:

export PATH='/usr/local/bin:/bin:/usr/bin'

Depending on your security risk and needs, you should also consider using absolute paths. This tends to be cumbersome and can be an issue where portability is concerned, as different operating systems put tools in different places. One way to mitigate these issues to some extent is to use variables. If you do this, sort them so you don’t end up with the same command three times because you missed it scanning the unsorted list.

One other advantage of this ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.