Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active April 7, 2024 23:38
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save magnetikonline/5172b4dafcdc079f28e60f512528c8a6 to your computer and use it in GitHub Desktop.
Save magnetikonline/5172b4dafcdc079f28e60f512528c8a6 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