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. 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|188.8.131.52|2404:6800:4007:801::1008' echo "$domain has $ip4 IPv4 and $ipv6 IPv6 address."
google.com has 184.108.40.206 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|220.127.116.11|2404:6800:4007:801::1008 i.theos.in|18.104.22.168|2600:807:320:305::3f6e:f648 cyberciti.biz|22.214.171.124|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 $ipv6 IPv6 address." done < "$_input"
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop