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.
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|22.214.171.124|2404:6800:4007:801::1008' echo "$domain has $ip4 IPv4 and $ipv6 IPv6 address."
google.com has 126.96.36.199 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|188.8.131.52|2404:6800:4007:801::1008 i.theos.in|184.108.40.206|2600:807:320:305::3f6e:f648 cyberciti.biz|220.127.116.11|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"Tweet itFacebook itGoogle+ itPDF itFound an error/typo on this page?