Bash / KSH: Define Delimiter (IFS) While Using read Command

How do I can set IFS (internal field separator) while using read command in bash loops?

The IFS variable is used in as the input field separator. If you set IFS to | (i.e. IFS=| ), | will be treated as delimiters between words/fields when splitting a line of input. [donotprint][/donotprint]In the read command, IFS is used to split the line of input so that each variable gets a single field of the input. The default value is . You can print it with the following command:

cat -etv <<<"$IFS"

Sample outputs:


In this example, read first and last name using read command and set IFS to a white space:

IFS=' ' read -p 'Enter your first and last name : ' first last 
echo "Hello, $first $last"

Sample outputs:

Enter your first and last name : SXI ADMIN

In this example set IFS to | and read data:

IFS='|' read domain ip4 ip6 <<< '||2404:6800:4007:801::1008'
echo "$domain has $ip4 IPv4 and $ipv6 IPv6 address."

Sample outputs: has IPv4 and  IPv6 address.

while loop example with IFS and read command

Create a text file (named foo.txt) as follows:
$ cat foo.txt
Sample outputs:||2404:6800:4007:801::1008||2600:807:320:305::3f6e:f648||2600:807:320:305::3f6e:f649

Create a bash shell script as follows:

# set IFS (internal field separator) to |
# read file using while loop
while IFS='|' read -r domain ip4 ip6 
   echo "$domain has $ip4 IPv4 and $ip6 IPv6 address."
done < "$_input"

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

How to Make Website WCAG Compliant?

Next Post

Link download Kali Linux 2020.1 (ISO + Torrent)

Related Posts