style(unitproc/):Shorten names of template prefix (bktemp -> bkt)
[BK-2020-03.git] / unitproc / bkt-checkIsInArray
diff --git a/unitproc/bkt-checkIsInArray b/unitproc/bkt-checkIsInArray
new file mode 100644 (file)
index 0000000..15d2fab
--- /dev/null
@@ -0,0 +1,82 @@
+#!/usr/bin/env bash
+
+yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
+die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
+try() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
+checkIsInArray() {
+    # Desc: Checks if input arg is element in array
+    # Usage: checkIsInArray arg1 arg2
+    # Version: 0.0.1
+    # Input: arg1: test string
+    #        arg2: array
+    # Output: exit code 0 if test string is in array; 1 otherwise
+    # Example: checkIsInArray "foo" "${myArray[@]}"
+    # Ref/Attrib: [1] How do I check if variable is an array? https://stackoverflow.com/a/27254437
+    #             [2] How to pass an array as function argument? https://askubuntu.com/a/674347
+    local return_state input arg1 arg2 string_test
+    local -a array_test
+    input=("$@") # See [2]
+    arg1="${input[0]}";
+    arg2=("${input[@]:1}");
+    #yell "DEBUG:input:${input[@]}";
+    #yell "DEBUG:arg1:${arg1[@]}";
+    #yell "DEBUG:arg2:${arg2[@]}";
+
+    string_test="$arg1";
+    array_test=("${arg2[@]}");
+
+    #yell "DEBUG:string_test:$string_test";
+    #yell "DEBUG:$(declare -p array_test)";
+    for element in "${array_test[@]}"; do
+       #yell "DEBUG:element:$element";
+       if [[ "$element" =~ ^"$string_test" ]]; then
+           return_state="true";
+           continue;
+       fi;
+    done;
+    
+    # Report exit code
+    if [[ $return_state == "true" ]]; then
+       return 0;
+    else
+       return 1;
+    fi;
+} # Check if string is element in array
+
+# Sample test code
+my_array=("jan" "feb" "mar" "apr");
+yell "Array contains:${my_array[@]}";
+test_string="feb";
+yell "Checking to see if $test_string is in array...";
+if checkIsInArray "$test_string" "${my_array[@]}"; then
+    yell "\"$test_string\" is in array";
+else
+    yell "\"$test_string\" is not in array";
+fi;
+yell ""; # debug
+
+sleep 1;
+
+my_array=("jan" "feb" "mar" "apr");
+yell "Array contains:${my_array[@]}";
+test_string="oct";
+yell "Checking to see if $test_string is in array...";
+if checkIsInArray "$test_string" "${my_array[@]}"; then
+    yell "\"$test_string\" is in array";
+else
+    yell "\"$test_string\" is not in array";
+fi;
+yell ""; # debug
+
+sleep 1;
+
+my_array=("jan" "feb" "mar" "apr");
+yell "Array contains:${my_array[@]}";
+test_string="feb mar";
+yell "Checking to see if $test_string is in array...";
+if checkIsInArray "$test_string" "${my_array[@]}"; then
+    yell "\"$test_string\" is in array";
+else
+    yell "\"$test_string\" is not in array";
+fi;
+yell ""; # debug