[CentOS] Off Topic bash question

Thu Jul 23 14:41:38 UTC 2020
Gianluca Cecchi <gianluca.cecchi at gmail.com>

On Thu, Jul 23, 2020 at 4:25 PM Anand Buddhdev <anandb at ripe.net> wrote:

> On 23/07/2020 15:46, Jerry Geis wrote:
>
> Hi Jerry,
>
> See below, inline, for some comments.
>
>
> > 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"
>
>
I would add these considerations:
1) -r means to not consider \ character as an escape character so possibly
is not important to use it in your scenario
2) read support multiple variables parsing
3) read word separation (default space) can be modified using IFS (internal
field separator)

So I would change the script this way, together with other considerations

#!/bin/bash
#
IFS=','

index=0
total=0
names=()
ip=()
#while read -r LINE
while read NODENAME IP
do
#NODENAME=$(echo $LINE | cut -f 1 -d ',')
#IP=$(echo $LINE | cut -f 2 -d ',')
names[$((index++))]="$NODENAME"
ip[$((index++))]="$IP"
((total))
done < /tmp/list.txt

to verify you can add something like:

for i in ${names[@]} ${ip[@]}
do
echo $i
done

HIH,
Gianluca