I'm about to fall asleep, but I don't think there's a problem with what you're trying to do with sort. There is very likely a problem with the script's logic that's causing weird output. Here's why I say that.
I made a simple script, using the test data you gave:
Code:
#!/bin/bash
echo -e "one\nduplicate\ntwo\ntwo\nthree\nthree\ntwo\nthree" | sort -u
the output:
Code:
duplicate
one
three
two
So, sort works as you expect. So the problem must be in the script logic. I can't debug it completely, but I do see a potential problem: you're doing no error-checking at all.
To emphasize the point, what happens if one of the groups in the comma-separated list given by the user doesn't exist, or there's a typo? That can wreak havoc on your assignment to firstgrp. If no match is found, then you'll grep for an empty string between to colons (e.g. "::") on /etc/passwd. I'd be willing to bet that will turn up some matches for non-human accounts, but the script will just keep on processing.