Tim
Tim

Reputation: 11

Nested loops seem to skip over second loop in Bash

I am trying to write a script that:

a) reads the content of a .csv file

b) sets a variable to the value in the first position (ie to the left of the comma)

c) compare the variable value to each position in an array. If the value is in the array execute one command, if it isn't, insert that value into the first available slot in the array.

The .csv file is in the format:

co:7077,he17208am3200816internet.pdf,he17208am3200917internet.pdf co:7077,he17208am3200817internet.pdf,he17208am3200918internet.pdf co:7077,he17208am3200818internet.pdf,he17208am3200919internet.pdf co:7077,he17208am3200819internet.pdf,he17208am3200915internet.pdf co:7162,tra210051internet.pdf,tra21005101internet.pdf co:7162,tra210051appinternet.pdf,tra21005102internet.pdf co:7178,tra4157l11201021internet.pdf,tra4158l11201021internet.pdf co:7178,tra4157l11201022internet.pdf,tra4158l11201022internet.pdf

My script so far looks like:

#!/bin/bash

declare -a array
anum=0
src=source.csv
pid=0

while read line;
do
pid=$( echo $line | awk '{print$1}' FS=",")

  for n in "${array[@]}";
     do

        if [[ "$pid" = "$n" ]] ;
         then

          echo Duplicate value: "$pid";

         else
          array[$anum]="$pid"
          anum=$(( $anum +1 ))
        fi
     done
done < $src

echo ${array[@]}

When the script is executed the pid is successfully set and reset with each iteration of the while loop, but apparently the nested for loop is never ran.

From my google'ing I suspect it has something to do with the pipe in pid line, but I'll be buggered if I can figure out how to make it work.

Any help is greatly appreciated.

Upvotes: 1

Views: 569

Answers (3)

user133633
user133633

Reputation:

why did you use double square brackets? and also you used a single equals rather than double in the if?

try these one-liners...

$ if [ "a" == "b" ] ; then echo hello ; fi

$ if [ "a" == "a" ] ; then echo hello ; fi

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 360143

Set a flag in the else clause instead of adding the array element there. After your for loop if the flag is set, add the array element. Don't forget to unset the flag.

You can do array[anum++] without the next line or (( anum++ )) instead of anum=$(($anum + 1)).

Also: while IFS=, read -r pid discard if you don't need the rest of the line (you could do it a little differently if you need it). Doing this, you won't need the echo and awk.

Upvotes: 0

dogbane
dogbane

Reputation: 274630

You're not populating your array. The for loop is never executed because the array is empty.

Upvotes: 2

Related Questions