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. 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
cat -etv <<<"$IFS"
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"
Enter your first and last name : Vivek Gite Hello, Vivek Gite
In this example set IFS to | and read data:
IFS='|' read domain ip4 ip6 <<< 'google.com|18.104.22.168|2404:6800:4007:801::1008' echo "$domain has $ip4 IPv4 and $ipv6 IPv6 address."
google.com has 22.214.171.124 IPv4 and IPv6 address.
while loop example with IFS and read command
Create a text file (named foo.txt) as follows:
$ cat foo.txt
google.com|126.96.36.199|2404:6800:4007:801::1008 i.theos.in|188.8.131.52|2600:807:320:305::3f6e:f648 cyberciti.biz|184.108.40.206|2600:807:320:305::3f6e:f649
Create a bash shell script as follows:
#!/bin/bash _input="foo.txt" # set IFS (internal field separator) to | # read file using while loop while IFS='|' read -r domain ip4 ip6 do echo "$domain has $ip4 IPv4 and $ip6 IPv6 address." done < "$_input"