Viktor
Viktor

Reputation: 81

Bash array - do something with members that moved their position

I have following simplified script with array variable:

array1=(`somecommand1`)

for i in ${array1[@]} ; do
echo $1
done

That will give me following output:

 1 277788
 2 283871
 3 282913
 4 283519
 5 283568
 6 283563
 7 283595
 8 278229
 9 283029
10 278654
11 280508
12 248825
13 282361
 . 

On each script run, when the ${array1} changes, I need to run some command on those numbers that moved to the top of the array plus I want to check one that likely stayed unchanged issuing checkcmd that will get a timestamp and compares it with the timestamp from previous run.

 1 283563 <- moved=modified
 2 283871 <- moved=modified (overtook 277788)
 3 277788 <- modified? `checkcmd 277788` timestamp changed = modified, so check the #4
 4 282913 `checkcmd 282913` -> timestamp unchanged -> do not check further
 5 283519
 6 283568
 7 283595
 8 278229
 9 283029
10 278654
11 280508
12 248825
13 282361

Now I want to run somecommand2 on those numbers identified as modified perhaps using another array:

array2=( 283563 283871 277788 )
for i in ${array2[@]} do
somecommand2 $i
done

How can I achieve that? I do not want to run checkcmd on each ${array1} member, because each checkcmd takes quite long to execute due to polling data from the server and there could be even hundreds of members in ${array1} so it would make this script unusable. I hope there will be some "function" that will compare arrays with each other like that and the checkcmdcan be run only once or twice as per logic explained above.

Upvotes: 0

Views: 48

Answers (2)

omoman
omoman

Reputation: 859

Another way of printing with index, using a c-style loop

for (( i=0; i<${#arr1[@]}; ++i )); do
    echo $i ${arr1[i]}
done

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247022

  1. keep a counter:

     n=0; for i in "${array1[@]}"; do printf "%2d %s\n" $((++n)) "$i"; done
    
  2. You'll need to compare them

    for idx in "${array1[@]}"; do
        if (( ${array1[idx]} == ${array2[idx]} )); then
            echo "they are the same: ${array1[idx]}"
        else
            echo "they are the same: ${array1[idx]} <=> ${array2[idx]}"
        fi
    done
    

Upvotes: 1

Related Questions