Bash - IFS (Field Separator)

1 - About

The field separator is a set of character that defines one or more field separator that separates (delimit) fields 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 variable $IFS

When passing a string to a function, the parameters will be parsed with this value before being assigned.
The backslash statement break character is the equivalent of an IFS character ie:

command \
  arg1 \
  arg2

is equivalent to


command "$IFS" arg1 "$IFS" arg2

3 - 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!)

4 - Management

4.1 - 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"

  • Proof with sed that will replace the tab \t into an arrow

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


4.2 - Default

IFS default value is the following whitespace character

  • space,
  • horizontal tab,
  • and newline

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


echo "$IFS" | cat -vte


^I$
$

where we see

  • a space
  • ^I which means a tab
  • $ which means a end of line

Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap