Skip to content

Instantly share code, notes, and snippets.

@ns408
Forked from magnetikonline/README.md
Created March 14, 2018 07:31
Show Gist options
  • Save ns408/b731ebf577121963f2b8ab2065c5ed0d to your computer and use it in GitHub Desktop.
Save ns408/b731ebf577121963f2b8ab2065c5ed0d to your computer and use it in GitHub Desktop.
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