i am in my initial learning phase of unix. i was going thru the function part.
below is the example which was there but i am not able to understand logic and the use of IFS(internal field separator)
lspath() {
OLDIFS="$IFS"
IFS=:
for DIR in $PATH ; do echo $DIR ; done
IFS="$OLDIFS"
}
the output is below. here i am failed to understand how the o/p is coming like below
and logic behind the IFS.
IFS The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''.
The shell you are using always tries to "expand" your command line, i.e. separates it into words, which in turn it then treats according to different rules, cf. man page of your shell.
In order to separate the line, the shell needs to know where words start and end. This is where IFS comes into play. Usually set to <space>,<tab>,<newline> characters for normal command lines, you can set it to what you want by assigning a new value. Doing this, it's safe to save the old value(s). In your example, the PATH environment variable looks like sth like /sbin:/bin:/usr/bin:/usr/sbin... (must be a root user), a colon separated list. IFS=: tells the shell to separate exactly there when supplying parameters to the for construct.
When a shell starts, the IFS variable may be inherited from the environment or initialized by the shell to <space>, <tab>, and <newline> in that order. If IFS is unset (which is very different from setting IFS to an empty string), the shell and the read speical built-in utility split fields as if IFS had been set to <space>, <tab>, and <newline> in that order.
When you need to use non-default word splitting (e.g., using : as the field separator when grabbing directories out of $PATH), saving the old value and restoring it after you have completed the need for special word splitting actions is just good programming practice. In the example code given, OLDIFS is used to save the old value of IFS before setting IFS to : . After $PATH is split, setting IFS to OLDIFS restores its original value (as long as it hadn't been unset).
Whether or not IFS is exported doesn't matter for this discussion.
What did you expect after reading Don's and my explanations (or - maybe - not?)? You have a space separated input and try to separate it by colons. The shell will of course use $x as one single lump of chars, assign it to t unmodified, and echo it as is.