Jay Taylor's notes
back to listing indexBash: check if an array contains a value - Stack Overflow
[web search]
In Bash, what is the simplest way to test if an array contains a certain value? EDIT: with help from the answers and the comments, after some testing, I came up with this:
I'm not sure if it's the best solution, but it seems to work. | ||||
add comment | ||||
There is sample code that shows how to replace a substring from an array. You can make a copy of the array and try to remove the target value from the copy. If the copy and original are then different, then the target value exists in the original string. The straightforward (but potentially more time-consuming) solution is to simply iterate through the entire array and check each item individually. This is what I typically do because it is easy to implement and you can wrap it in a function (see this info on passing an array to a function).
| ||||
add comment |
For strings:
| |||||||||||||||||||||||||||||||||
|
If you want to do a quick and dirty test to see if it's worth iterating over the whole array to get a precise match, Bash can treat arrays like scalars. Test for a match in the scalar, if none then skipping the loop saves time. Obviously you can get false positives.
This will output "Checking" and "Match". With | |||
add comment |
| |||||||||
|
Here is a small contribution :
Note: this way doesn't distinguish the case "two words" but this is not required in the question. | |||
add comment |
Below is a small function for achieving this. The search string is the first argument and the rest are the array elements:
A test run of that function could look like:
| |||||||||
|