Setting a Secure $IFS

Problem

You want to make sure your Internal Field Separator environment variable is clean.

Solution

Set it to a known good state at the beginning of every script using this clear (but not POSIX-compliant) syntax:

# Set a sane/secure IFS (note this is bash & ksh93 syntax only--not portable!)
IFS=$' \t\n'

Discussion

As noted, this syntax is not portable. However, the canonical portable syntax is unreliable because it may easily be inadvertently stripped by editors that trim whitespace. The values are traditionally space, tab, newline—and the order is important. $*, which returns all positional parameters, the special ${!prefix@} and ${!prefix*} parameter expansions, and programmable completion, all use the first value of $IFS as their separator.

The typical method for writing that leaves a trailing space and tab on the first line:

1 IFS=' • → ¶
2 '

Newline, space, tab is less likely to be trimmed, but changes the default order, which may result in unexpected results from some commands.

1 IFS='• ¶
2 • → '

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.