what is IFS in a bash script

pls explain  what this is doing and the role of IFS.
these are examples

Word Splitting
The results of parameter and arithmetic expansions, as well as command substitution, are subjected to word splitting if they were not quoted:

Word splitting is based on the value of the internal field separator variable, IFS. The default value of IFS contains the whitespace characters of space, tab, and newline (IFS=$' \t\n'). When IFS has its default value or is unset, any sequence of default IFS characters is read as a single delimiter.


$ var='   spaced
   out   '
$ sa $var
:spaced:
:out:

If IFS contains another character (or characters) as well as whitespace, then any sequence of whitespace characters plus that character will delimit a field, but every instance of a nonwhitespace character delimits a field:


S IFS=' :'
$ var="qwerty  : uiop :  :: er " ## :  :: delimits 2 empty fields
$ sa $var
:qwerty:
:uiop:
::
::
:er:

If IFS contains only nonwhitespace characters, then every occurrence of every character in IFS delimits a field, and whitespace is preserved:


$ IFS=:
$ var="qwerty  : uiop :  :: er "
$ sa $var
:qwerty  :
: uiop :
:  :
::
: er :


TIMFOX123Asked:
Who is Participating?
 
TintinConnect With a Mentor Commented:
Well, you've already posted an explanation, so perhaps some more examples would help.

Assume that file.dat has the following data

one two
three fou

Open in new window

r

You could read these fields with the following loop

while read f1 f2
do
   echo "field1=$f1"
   echo "field2=$f2"
done <file.dat

Open in new window



now assume file.dat has the following data

one,two
three,four

Open in new window


to be able to read and process it the same as the last set of code, you need to set IFS to a comma.

IFS=','
while read f1 f2
do
   echo "field1=$f1"
   echo "field2=$f2"
done <file.dat[

Open in new window


0
 
NetExpert-WarszawaCommented:
IFS specifies characters that a shell recognizes as word separators. It helps the shell to know how to split a string into separate words.
0
 
omarfaridCommented:
IFS is input field separator. By default space is the filed separator. If you need to set it to something else, you use IFS.

0
 
NetExpert-WarszawaCommented:
IFS is the space, tab, and newline characters by default
0
 
TIMFOX123Author Commented:
thank you

great job all
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.