I'm just looking for a proper and more elegant way of writing the following code in Bash:
in_array() {
local somearray=${1}[@]
local somevalue=${2}
for i in ${!somearray}; do
if [[ ${i} == ${somevalue} ]]; then
return 0
fi
done
return 1
}
#declare array
declare -a myArray=(foo bar baz qux)
#defined values
val1=foo
val2=baz
#Ugly check if multiple strings are part of the array at the same time
if in_array myArray $val1 && in_array myArray $val2; then
# Do something #
else
# Do something else#
fi
The basic idea is that I need to check if 2 ore more static values are, at the same time, part of the array.
Wondering if there's a better way of doing this, because if I'll need to check for more than 3-4 values... that if in_array
line will get huge.
Any suggestion, please?
Thank you!
"$(foo, bar, baz, qux)"
should probably have been(foo bar baz qux)
,$val22
should be$val2
.-->
check the answers from those links... for example when they suggest=~
(for the ugliness - it's more readable ) or when they propose to flatter the array and search the substring*"two"*
(you can try*$var1*
&&*$var1*
) ... BTW I think you can agree better is really relative...:-)
better to read, better because more efficient (you need to use a different function as your answer... to break the 1st time you do not find...)...?