Interview Scripting (Bash, Groovy)

What does IFS do, and why set it when reading lines? [Basic]

Answer

IFS is the Internal Field Separator. Bash uses it for word splitting and read field splitting. When reading whole lines, I often set IFS= for that read command so leading and trailing whitespace is preserved.

Technical explanation

The default IFS includes space, tab, and newline, which can unintentionally trim or split input.

Setting IFS locally for one read avoids changing global shell behavior.

IFS can also be used intentionally to split delimited data, such as CSV-like simple fields, but CSV with quoting needs a real parser.

Hands-on example

line=" alpha beta "

while IFS= read -r value; do

printf '<%s>

' "$value"

done <<< "$line"

IFS=: read -r user _ uid _ _ home shell < <(getent passwd "$USER")

echo "$user $uid $home $shell

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions