[CentOS] Off Topic bash question

Thu Jul 23 14:39:45 UTC 2020
Anand Buddhdev <anandb at ripe.net>

On 23/07/2020 15:46, Jerry Geis wrote:

Hi Jerry,

You can do even better:

index=0
total=0
names=()
ip=()

IFS=,

while read -r NODENAME IP
do
   names[$index]="$NODENAME"
   ip[$((index++))]="$IP"
   ((total++))
done < list.txt

In this example, you set the input field separator (IFS) to the comma, 
so that the shell does the word splitting for you, and then allow the 
"read" call to assign to both variables in a single call. Now you don't 
need any "cut" calls. In fact, this example avoids forks completely, by 
just using native features of bash.

For small inputs, it doesn't matter, but if you were processing a large 
file, and your script was forking for each call to "cut" and creating a 
new process, you would incur a horrible amount of overhead for no reason.

Regards,
Anand

> I have a simple script:
> #!/bin/bash
> #
> index=0
> total=0
> names=()
> ip=()
> while read -r LINE
> do
> NODENAME=`   echo $LINE | cut -f 1 -d ','`
> IP=`         echo $LINE | cut -f 2 -d ','`
> names[index]="$NODENAME"
> ip[index]="$IP"
> index=`expr index+1`
> total=`expr total+1`
> done <<< $(cat list.txt)
> 
> simple file:
> more list.txt
> name1,ip1
> name2,ip2
> name3,ip3
> 
> output when running:
>   sh -x ./test_bash.sh
> + index=0
> + total=0
> + names=()
> + ip=()
> ++ cat list.txt
> + read -r LINE
> ++ echo name1,ip1 name2,ip2 name3,ip3
> ++ cut -f 1 -d ,
> + NODENAME=name1
> ++ echo name1,ip1 name2,ip2 name3,ip3
> ++ cut -f 2 -d ,
> + IP='ip1 name2'
> + names[index]=name1
> + ip[index]='ip1 name2'
> ++ expr index+1
> + index=index+1
> ++ expr total+1
> + total=total+1
> + read -r LINE
> + echo name1
> name1
> 
> 
> Question is why is it not reading one line at a time ?
> All I get is the first one.
> I'm just trying to build the array of the items in the file and then list
> them at this point.
> 
> Thanks
> 
> Jerry
> _______________________________________________
> CentOS mailing list
> CentOS at centos.org
> https://lists.centos.org/mailman/listinfo/centos
>