Table of Contents

Bash - IFS (Field Separator)

About

The field separator is a set of character that defines one or more field separator that separates (delimit) field (word) in a string.

This NOT a atomic string separator but a set of single-character string separator ie

IFS="DELIM"

will define 5 characters separators, respectively: D, E, L, I and M

It's defined in the IFS variable 1)

When passing a string to a function, the parameters will be parsed with this value before being assigned. See What is Word Splitting (or Word expansion) in Bash ?

The backslash statement break character is the equivalent of an IFS character ie:

command \
  arg1 \
  arg2

is equivalent to

command "$IFS" arg1 "$IFS" arg2

Example

#!/bin/bash
output_args()
{
  for arg
  do
    echo -e '('"$arg"')'
  done
}

var=$'hello Nico\nHello Nico!'
echo "IFS is a return \n"
IFS=$'\n'
output_args $var

echo IFS is a space
IFS=' '
output_args $var
IFS is a return \n
(hello Nico)
(Hello Nico!)
IFS is a space
(hello)
(Nico
Hello)
(Nico!)

Management

Print

As the IFS character has a lot of chance to be a non-printing character, don't forget quote it with an echo command

Example:

echo "$IFS"
IFS=$'\t'; echo "$IFS"  | sed 's/\t/→/g;'

Default

IFS default value is the following whitespace character

You can find it out with the following command that uses cat -vte to show the whitespace characters

 echo "$IFS" | cat -vte
^I$
$

where we see