style(user/bkytpldl-generic):Adjust comment
[BK-2020-03.git] / unitproc / bkt-checkIsInArray
1 #!/usr/bin/env bash
2
3 yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
4 die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
5 try() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
6 checkIsInArray() {
7 # Desc: Checks if input arg is element in array
8 # Usage: checkIsInArray arg1 arg2
9 # Version: 0.0.1
10 # Input: arg1: test string
11 # arg2: array
12 # Output: exit code 0 if test string is in array; 1 otherwise
13 # Example: checkIsInArray "foo" "${myArray[@]}"
14 # Ref/Attrib: [1] How do I check if variable is an array? https://stackoverflow.com/a/27254437
15 # [2] How to pass an array as function argument? https://askubuntu.com/a/674347
16 local return_state input arg1 arg2 string_test
17 local -a array_test
18 input=("$@") # See [2]
19 arg1="${input[0]}";
20 arg2=("${input[@]:1}");
21 #yell "DEBUG:input:${input[@]}";
22 #yell "DEBUG:arg1:${arg1[@]}";
23 #yell "DEBUG:arg2:${arg2[@]}";
24
25 string_test="$arg1";
26 array_test=("${arg2[@]}");
27
28 #yell "DEBUG:string_test:$string_test";
29 #yell "DEBUG:$(declare -p array_test)";
30 for element in "${array_test[@]}"; do
31 #yell "DEBUG:element:$element";
32 if [[ "$element" =~ ^"$string_test" ]]; then
33 return_state="true";
34 continue;
35 fi;
36 done;
37
38 # Report exit code
39 if [[ $return_state == "true" ]]; then
40 return 0;
41 else
42 return 1;
43 fi;
44 } # Check if string is element in array
45
46 # Sample test code
47 my_array=("jan" "feb" "mar" "apr");
48 yell "Array contains:${my_array[@]}";
49 test_string="feb";
50 yell "Checking to see if $test_string is in array...";
51 if checkIsInArray "$test_string" "${my_array[@]}"; then
52 yell "\"$test_string\" is in array";
53 else
54 yell "\"$test_string\" is not in array";
55 fi;
56 yell ""; # debug
57
58 sleep 1;
59
60 my_array=("jan" "feb" "mar" "apr");
61 yell "Array contains:${my_array[@]}";
62 test_string="oct";
63 yell "Checking to see if $test_string is in array...";
64 if checkIsInArray "$test_string" "${my_array[@]}"; then
65 yell "\"$test_string\" is in array";
66 else
67 yell "\"$test_string\" is not in array";
68 fi;
69 yell ""; # debug
70
71 sleep 1;
72
73 my_array=("jan" "feb" "mar" "apr");
74 yell "Array contains:${my_array[@]}";
75 test_string="feb mar";
76 yell "Checking to see if $test_string is in array...";
77 if checkIsInArray "$test_string" "${my_array[@]}"; then
78 yell "\"$test_string\" is in array";
79 else
80 yell "\"$test_string\" is not in array";
81 fi;
82 yell ""; # debug