]> git.corax.cc Git - toolbox/commitdiff
include/array: Add function for checking if an element is in an array
authorMatthias Kruk <m@m10k.eu>
Wed, 24 Mar 2021 22:24:30 +0000 (07:24 +0900)
committerMatthias Kruk <m@m10k.eu>
Wed, 24 Mar 2021 22:24:30 +0000 (07:24 +0900)
Bash doesn't provide a simple way to check if an element is in an array.
This commit adds the array_contains convenience function to solve that
problem.

include/array.sh [new file with mode: 0644]

diff --git a/include/array.sh b/include/array.sh
new file mode 100644 (file)
index 0000000..2ff4b28
--- /dev/null
@@ -0,0 +1,23 @@
+#!/bin/bash
+
+__init() {
+       return 0
+}
+
+array_contains() {
+       local needle
+       local haystack
+
+       local cur
+
+       needle="$1"
+       haystack=("${@:2}")
+
+       for cur in "${haystack[@]}"; do
+               if [[ "$needle" == "$cur" ]]; then
+                       return 0
+               fi
+       done
+
+       return 1
+}