1

Similar to how in python you can do 'if letter in string:', I'm trying to imitate this in bash. The code is below:

SYMBOLS="ABC"
msg="alskdfjAasdksdfh!?asdflkjhghrg"

# Loops through each letter in the variable msg individually
for (( i=0; i<${#real_message}; i++ )); do
    # Assigns the current letter to the variable
    letter="${msg:$i:1}"

    # This is the part I have a question about
    if [[ $msg == *"$SYMBOLS"* ]]; then
        echo "Found."
    fi
done

However, the if statement doesn't work. What's supposed to happen is anytime it grabs a character to be stored in the variable 'letter', it should check if that character exists in the variable 'SYMBOLS'.

For example, msg has the character 'A' in it, so when 'letter' iterates through and gets to 'A', it should echo "Found." indicating the if statement works. However, this doesn't work obviously because I'm not understanding something correctly. Just for clarification: it isn't looking for substrings containing "ABC", it's looking for either "A", "B", or "C" when it's stored in the 'msg' variable.

bmcisme
  • 57
  • 6
  • 2
    It should be `[[ "$SYMBOLS" == *"$letter"* ]]` – Barmar Feb 13 '20 at 00:06
  • You can also use a regular expression without looping. `if [[ $msg =~ [ABC] ]]` – Barmar Feb 13 '20 at 00:08
  • @Flux This helps to find a substring but it doesn't help to check individual letters in SYMBOL. It only provides ways to find occurrences of substrings containing "ABC". I'm wanting ways to find occurences of A, B, or C, but not ABC together. If that makes sense... – bmcisme Feb 13 '20 at 00:15
  • I'm pretty sure my suggestion does that. `[ABC]` means any of those characters, not the whole string `ABC`. – Barmar Feb 13 '20 at 00:17
  • And with the first version, when `$letter` is `A`, it's doing `if [[ ABC == *A*` ]]` which is what you want. – Barmar Feb 13 '20 at 00:17
  • Your code looks for the whole substring, instead of looking for single letters. – Barmar Feb 13 '20 at 00:19
  • @Barmar I missed your comment at the top for some reason, this solved it. Thank you! – bmcisme Feb 13 '20 at 00:21

0 Answers0