rizwan
rizwan

Reputation: 117

Understanding for loop

Can someone help me to understand below code

I am resetting IFS to newline in 2nd line of the script itself. This value is read by out for command . Inside inner for command i am resetting IFS value to :

1) How IFS value is getting reset to New Line again after the first iteration of the outer loop as outer for loop is beginning from 3rd line and i am assigning newline character to IFS in 2nd line .

2) When i am doing echo $IFS in the outer loop and inner loop it is coming as blank. Any idea why.

Can someone explain how does this work

test.txt:

cat test.txt

oracle:dba
network:admin
system:engineer

test.sh:

cat test.sh

#!/bin/bash
# changing the IFS value

IFSOLD=$IFS
IFS=$'\n'
for entry in $(cat test.txt)
do
    echo "Values in $entry "
    IFS=:
    for value in $entry
    do
      echo " $value"
    done
done



sh test.sh

Values in oracle:dba
 oracle
 dba
Values in network:admin
 network
 admin
Values in system:engineer
 system
 engineer

Upvotes: 0

Views: 53

Answers (2)

chepner
chepner

Reputation: 530920

Don't use a for loop to iterate over the lines of a file; use a while loop.

Then use read to split each line into an array of individual values.

while IFS= read -r entry; do
    echo "Values in $entry"
    IFS=: read -a values <<< "$entry"
    for value in "${values[@]}"; do
        echo " $value"
    done
done < test.txt

Upvotes: 0

Barmar
Barmar

Reputation: 780724

IFS doesn't need to be reset for the outer loop. The result of $(cat test.txt) is split using IFS before the loop starts, it isn't split again each time through the loop.

Upvotes: 2

Related Questions