Python has a "set" type which contains unique objects. Does Bash have something equivalent?
I want to keep adding elements to such a bash "set" and never have duplicates.
Python has a "set" type which contains unique objects. Does Bash have something equivalent?
I want to keep adding elements to such a bash "set" and never have duplicates.
After some googling I found a nice bash implementation at http://www.catonmat.net/blog/set-operations-in-unix-shell-simplified/. It has all the usual set operators in multiple ways, and even a printable pdf cheatsheet.
I've used associative arrays though, it's much more readable.
Declare a
setA
associative array variable:Or declare and add the initial members at the same time:
Add a member to the set:
Test for membership:
List members:
or:
Cardinality (number of members in the set):
Remove a member:
Bash 4.0 has associative arrays, which can be used to build sets.
Here's an article that discusses them (it was the first Google hit for "bash associative arrays").
(Personally, I'd just use something other than bash, probably Perl.)
gives
also in bash 3, where no associative arrays are available