I want to remove the IP's as defined in "bb" array from "aa" array so the IP's and will be removed from the list in aa array.

When I run my ksh code and later print the array aa, I see that the IP - was not deleted?

What's wrong in my syntax?

   echo ${aa[*]}

   echo ${bb[*]}

ksh program:

  for run in  ${bb[*]}
   for ((i=0; i<${#aa[@]}; i++)); do
   [[ ${aa[i]} == $run ]] && unset aa[i]


 echo ${aa[*]}                  

NOTE: should be deleted from the above list.

  • @sim maybe it will be better to transfer my question to stackoverflow – yael Jun 23 '13 at 15:32
  • 1
    your code works for me. What is the value of IFS in your environment? – iruvar Jun 23 '13 at 15:47
  • each IP is separately IP as the following aa[1]= aa[2]= aa[3]= aa[4]= bb[1]= bb[2]= – yael Jun 23 '13 at 15:57
  • can you try for run in "${bb[@]}" instead of for run in ${bb[*]} and see? – iruvar Jun 23 '13 at 16:09
  • 1
    interesting. I am unable to reproduce your issue. We may be on different versions of ksh. You may want to add your ksh version to the question. All the best. – iruvar Jun 23 '13 at 16:30

I don't know why your code does not work for the presented inputs. It does on my system under ksh.

But your original code has a problem: the conditional part i<${#aa[@]} is fragile - since ${#aa[@]}, i.e. the array size is decremented after each unset - but the following array elements are not automatically shifted to the left. For your example

this does not make a difference - but it would make a difference for - say:

I improved the code with respect to that issue (note the assignment before loop entry). I also eliminated an inner loop (using an associative array) which improves the runtime from quadratic to linear:

$ cat x.sh

outputs it:

bb=([]=1 []=1)

print Size of input ${#aa[*]}
print Size of exclude list ${#bb[*]}

for ((i=0; i<$n; ++i))
  if [[ ${bb[${aa[i]}]} ]]
    print Removing element with index $i: ${aa[i]}
    unset aa[i];
  print New size of input ${#aa[*]}

print Resulting size of input ${#aa[*]}
print Resulting elements ${aa[*]}

for ((i=0; i<$n; ++i))
  print Index $i, Value 'a['$i']'=${aa[$i]}

It produces following output on Fedora 17:

$ ksh x.sh
Size of input 4
Size of exclude list 2
New size of input 4
Removing element with index 1:
New size of input 3
Removing element with index 2:
New size of input 2
New size of input 2
Resulting size of input 2
Resulting elements
Index 0, Value a[0]=
Index 1, Value a[1]=
Index 2, Value a[2]=
Index 3, Value a[3]=

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.