I'm trying to find a simple way to just test an array for duplicate values. It would be nice, but not completely necessary, to be able to identify the specific lines that have duplicates, but the important point is simply being able to see that there's a duplicate.
I have an array, $key_array
, which contains some numbers:
# echo ${key_array[@]} 1 2 3 4 3 3
This array could have an arbitrary number of numbers, some of which could be duplicates of others. They will be integer numbers only. (Numbers beginning with a 0
, such as 03
, should not make into the array at all, but in the off-chance that it happens, catching 3
and 03
as a duplicate of each other would be better than treating them as different numbers.)
I need to determine if any of these numbers are duplicates. I was thinking this could be done with an exit code if nothing else. What I was after was something like this:
if $(some command); then echo "Array contains duplicates." exit 1 fi $(commands to run after duplicate check)
The idea being in the end that the script informs the user and exits if there are duplicates (not super important to identify where the duplicates are, just telling the user to check for duplicates is enough), or if there aren't any duplicates, it proceeds and runs a bunch of other stuff.
How would I best accomplish this?
$()
inif $(some command); then
is not necessary. The if construct by default takes a list (a sequence of one or more pipelines) and executes them, testing their exit status. Thus,if some command; then
is sufficient.