Here is an example of behavior I want to achieve:
Suppose I have a list of lines, each line containing space separated values:
lines='John Smith
James Johnson'
And I want to loop over lines echoing name or surname only as user asked by prompt, so I change IFS globally:
oIFS=$IFS
IFS='
'
for line in $lines; do
IFS=$oIFS
read name surname <<< $line
read -p "Do you want to echo name? surname otherwise "
if [[ $REPLY == "y" ]]; then
echo $name
else
echo $surname
fi
done
This works, and yet this approach doesn't look sane for me:
- We change IFS and may forget to restore it
- We restore IFS every single iteration of the loop
I discovered that while IFS=...
can be used here like that:
while IFS='
' read line ; do
echo $line
read name surname <<< $line
read -p "Do you want to echo name? surname otherwise "
if [[ $REPLY == "y" ]]; then
echo $name
else
echo $surname
fi
done <<< "$lines"
But this is not an option because read -p
prompt gets corrupted by continuous input stream
A solution would be IFS set only for one for
statement like this:
IFS='
' for line in $lines; do
...
done
but bash disallows that.