Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active May 5, 2020 18:27
Embed
What would you like to do?
Bash internal field separator (IFS) usage.

Bash internal field separator (IFS) usage

The IFS internal variable is used to determine what characters Bash defines as word/item boundaries when processing character strings. By default set to whitespace characters of space, tab, and newline.

Running the example ifs.sh, comparing the difference between the default and setting only newline as a boundary we get the following output:

/path/to/first
file
/path/to/second
file
/path/to/third
file

/path/to/first file
/path/to/second file
/path/to/third file

Reference

#!/bin/bash -e
# create dummy input lines (think output of say, ls)
read -d '' INPUT_LINES <<EOF
/path/to/first file
/path/to/second file
/path/to/third file
EOF
# without IFS
for item in $(echo "$INPUT_LINES"); do
echo "$item"
done
echo
# with IFS
IFS=$'\n'
for item in $(echo "$INPUT_LINES"); do
echo "$item"
done
# reset back to default value
unset IFS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment