I have a script where I need to do all possible comparisons between the contents of a string variable. Each combination requires a different approach to the contents of the variable, so something like this:
if $a contains "a" AND "b" AND "c"; then do x
elif $a contains "a" AND "b" but NOT "c"; then do y
elif $a contains "b" AND "c" but NOT "a"; then do z
...
As far as I know, the way of doing that is constructing an if conditional like this one:
if [[ $A == *"b"* ]] && [[ $A == *"c"* ]] && [[ $A == *"d"* ]]
elif [[ $A == *"b"* ]] && [[ $A == *"c"* ]]
elif [[ $A == *"c"* ]] && [[ $A == *"d"* ]]
elif [[ $A == *"b"* ]] && [[ $A == *"d"* ]]
elif [[ $A == *"b"* ]]
elif [[ $A == *"c"* ]]
elif [[ $A == *"d"* ]]
fi
But that is of course too complicated to read, understand and write without mistakes, given that the name of my variable ($A) and the substrings (b, c, d) are way longer than that. So I wanted to see if there was a way of saving the contents of a conditional expression to a variable:
contains_b= *a condition for [[ $A == *"b"* ]]*; echo $contains_b
-> true | false
I only found the response here [contains_b=$(! [ "$A" = *"b"* ]; echo $?)
]; however, $contains_b -> 0
won't work in subsequent conditionals because:
if $contains_b; then do x; fi
-> bash: [0]: command not found
So the only solution that I could think of is doing it manually:
if [[ $A == *"b"* ]]; then
contains_b=true
else
contains_b=false
fi
However, I would end up doing the three if statements to get the three variables, and the other 7 comparisons for each of the different combinations.
I am wondering if there is a different/more efficient way of doing it. If not, do you have a suggestion for another way of doing these multiple comparisons? I feel that I am making it overly complicated...
Thank you for any help.
$A
? In your question you have 3, but how many is "way more"?