Reputation: 51
Let's have an array:
echo $run
CEADAPST CENIPT CEDAMT CEODST +ASM CEREMAFT
Let's look if some values are present in the array or not (second and forth values are correct yet they are not found):
for dbname in CEREMAF CEREMAFT CEREMAFg +ASM; do if [[ " ${run[@]} " =~ " ${dbname} " ]]; then echo "you're golden!"; else echo "nope"; fi; done
nope
nope
nope
nope
Let's remove the space expansion, whole idea was to avoid similar words and go only for exact match:
for dbname in CEREMAF CEREMAFT CEREMAFg +ASM; do if [[ ${run[@]} =~ ${dbname} ]]; then echo "you're golden!"; else echo "nope"; fi; done
you're golden!
you're golden!
nope
nope
We do get some matches in the last case but the first match is a false correct (only similar because we removed the space expansion) and the fourth is still not found (probably because of plus sign). I clearly misunderstood the concept I found here on SO but I was not able to make it working and man, I tried... Why it doesn't work?
Upvotes: 1
Views: 41
Reputation: 2762
use this function to handle that, it uses namereferening
and two nested iteration to get you your desired result
run=( CEADAPST CENIPT CEDAMT CEODST +ASM CEREMAFT );
arrayIn() {
local value=$1;
local -n array=$2;
local found=0;
for val in "${array[@]}";do
[[ "$val" != "$value" ]] && {
found=0;
} || {
found=1;
break;
}
done
(( found == 0 )) && return 1;
return 0;
}
for dbname in CEREMAF CEREMAFT CEREMAFg +ASM;do
arrayIn $dbname run
(( $? == 0 )) && { echo "yes"; } || echo "nope"
done
Upvotes: 1
Reputation: 37237
Try
for dbname in (whatever) \\+ASM; do ...
^^
Note the addition of double slashes.
From help [[
:
When the `=~' operator is used, the string to the right of the operator is matched as a regular expression.
So what does regex +ASM
mean? Nope, it's malformed. Escape the plus sign and it'll work
Upvotes: 1