Is there a nice way of checking if an array has an element in bash (better than looping through)?
Alternatively, is there another way to check if a number or string equals any of a set of predefined constants?
|
|
|
In Bash 4, you can use associative arrays:
To set up the array initially you could also do direct assignments:
or this way:
|
|||||||||||
|
|
It's an old question, but I think what is the simplest solution has not appeared yet:
Outputs:
To see how this work check this. |
||||
|
|
|
There is a way to test if an element of an associative array exists (not set), this is different from empty:
Then use it:
|
|||||||
|
|
You can see if an entry is present by piping the contents of the array to grep.
You can also get the index of an entry with grep -n, which returns the line number of a match (remember to subtract 1 to get zero-based index) This will be reasonably quick except for very large arrays.
explanation:
You can of course fold the subtraction into the command. But then test for -1 for missing:
|
||||
|
|
|
I don't think you can do it properly without looping unless you have very limited data in the array. Here is one simple variant, this would correctly say that
The problem is that there is no easy way to add the anchors (that I can think of) besides looping through the array. Unless you can add them before you put them in the array... |
|||
|