Re: Off Topic bash question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]



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

Hi Jerry,

See below, inline, for some comments.

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 ','`

NODENAME=$(cut -d, -f1 <<< $LINE)

Notes: use $( instead of backticks. There's no need to quote the comma. Write less and write concisely.

IP=`         echo $LINE | cut -f 2 -d ','`

IP=$(cut -d, -f2 <<< $LINE)

names[index]="$NODENAME"
ip[index]="$IP"

ip[$((index++))]="$IP"

This allows you to use the variable index, and then increment it by one for the next cycle of the loop.

index=`expr index+1`

Not needed because of the post-increment (++) above.

total=`expr total+1`

((total++))

done <<< $(cat list.txt)

done < list.txt

The "<<<" operator does all manner of expansion of the input and supplies it as a single line. That not what you want. Just redirect stdin from the file instead.

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

This is happening because of the <<< operator.

++ 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.
_______________________________________________
CentOS mailing list
CentOS@xxxxxxxxxx
https://lists.centos.org/mailman/listinfo/centos



[Index of Archives]     [CentOS]     [CentOS Announce]     [CentOS Development]     [CentOS ARM Devel]     [CentOS Docs]     [CentOS Virtualization]     [Carrier Grade Linux]     [Linux Media]     [Asterisk]     [DCCP]     [Netdev]     [Xorg]     [Linux USB]


  Powered by Linux