So I have an array with strings, and another string variable itself, and I want to do a process, when the variable is one of the element of the array. Can it be write an IF line, without checking all elements with a loop?
1 Answer
Bash now supports associative arrays, that is arrays which keys are strings:
declare -A my_associative_array
So, you could maybe turn your classical array into an associative one and get access to the entry you are looking for with a simple:
my_string="foo bar"
my_associative_array["$my_string"]="baz cux"
echo "${my_associative_array[$my_string]}"
echo "${my_associative_array[foo bar]}"
And to test the existence of a key:
if [ "${my_associative_array[$my_string]:+1}" ]; then
echo yes;
else
echo no;
fi
From bash manual:
${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing
is substituted, otherwise the expansion of word is substituted.
So, if the key $my_string is null or unset, ${my_associative_array[$my_string]:+1} expands to nothing, else to 1. The rest is just a classical use of the if bash statement combined with test ([]):
if [ 1 ]; then echo true; else echo false; fi
prints true while:
if [ ]; then echo true; else echo false; fi
prints false. If you prefer to consider null entries as any other existing entry, just omit the colon:
if [ "${my_associative_array[$my_string]+1}" ]; then
echo yes;
else
echo no;
fi
From bash manual:
Omitting the colon results in a test only for a parameter
that is unset.