ckonn wrote:
...
I would like to ask is it correct to compare a variable that has a value of a string with an array that has many elements as strings, like in the lines:
...
The short answer is no - If no index is supplied, array element 0 is assumed.
set -x and declare -p are your debugging friends
You have a couple of options:
1. Expand the array and use a pattern
2. Use a function to loop through the array
3. Use an associative array, where condition is the key
You might find
http://mywiki.wooledge.org/BashFAQ helpful. Lots of examples and doc.
See example below:
Code: Select all
#set -x
declare -a ans=("ok" "good" "very well" "excellent" "super")
declare -A aans=(["ok"]= ["good"]= ["very well"]= ["excellent"]= ["super"]=) # associate array
declare -l condition # give condition the lower case attribute so if OK is entered it becomes ok
# declare -p ans aans
printf -- '%s ' "${ans[@]}"; printf -- '\n'
### 1. Make condition a pattern and match against the entire expanded array
printf -- '----- test 1 -----\n'
read -r -p 'How are you today? ' condition # read -p option is a prompt. No need for the separate echo.
if [[ -n "${condition}" && "${ans[@]}" == *${condition}* ]]; then # notice the *condition*
printf -- "%s found\n" $condition
else
printf -- "%s not found\n" $condition
fi
### Create a function to loop through the array, break when found
printf -- '----- test 2 -----\n'
function condition_exists() {
local -- rc=1 # default not found
for element in "${ans[@]}"; do
if [[ ${condition} == "${element}" ]]; then
rc=0
break
fi
done
return $rc
}
read -r -p 'How are you today? ' condition
if condition_exists; then
printf -- "%s found\n" $condition
else
printf -- "%s not found\n" $condition
fi
### Use an associative array where the key is the expected condition
printf -- '----- test 3 -----\n'
read -r -p "How are you today? " condition
if [[ -n "${condition}" && -n "${aans[$condition]+set}" ]]; then
printf -- "%s found\n" $condition
else
printf -- "%s not found\n" $condition
fi