What is IFS in linux bash shell ?

1. Introduction

IFS stands for Internal Field Separator in Linux.

$IFS is one of the system variable with default value “space, tab, and a new line”.

This system variable signifies the end of one field or word in a line and from where another begins.

Internal Field Separator (IFS) is used for word splitting after expansion and helps to split lines into words by using read builtin command.


2. Default Value of IFS

default value is [space][tab][newline]


3. Examples

### Default behavior
[root@nglinux ~]# set x y z;  echo "$*"
x y z

### Setting IFS to ":"
[root@nglinux ~]# set x y z; IFS=":-;"; echo "$*"
[root@nglinux ~]# set x y z; IFS=":"; echo "$*"

IFS variable is used by our linux shell to determine how to do word splitting, i. e. how to recognize word boundaries and split words.


4. How to use IFS variable in shell Scripts.

### Lets define a variable str
[root@nglinux ~]# str="welcome:to:new:generation enterprise linux"

### Define IFS to ":" and see the magic
[root@nglinux ~]# IFS=":"; for word in $str; do echo "==> $word"; done
==> welcome
==> to
==> new
==> generation enterprise linux
[root@nglinux ~]# 

### Change IFS to space and see the change.
[root@nglinux ~]# IFS=" "; for word in $str; do echo "==> $word"; done
==> welcome:to:new:generation
==> enterprise
==> linux
[root@nglinux ~]# 

Similar to above scenario we can change IFS variable and do the word splitting.

Leave a Reply

Notify of