0

I am trying to create a loop that checks a string if it contains the characters "#" or " ". If it does contain this, it echos out 'yes', otherwise with echos 'no'.

#!/bin/bash

string="#### ## #  #### #"
for (( i=0; i<${#string}; i++ )); do
        str="${string:$i:1}"
        if ["$str"!="#"||"$str"!=" "];
                then
                        echo "No"
                        break
                else
                        continue
        fi
        echo "yes"
done
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    You have to reconsider your logic; every character is unequal to `#` or unequal to space. – Armali Apr 10 '21 at 11:12
  • 1
    What's your question? Shell script is not C; just use the built-in facilities, like `case $string in *[ #]*) echo yes;; *) echo no;; esac` – tripleee Apr 10 '21 at 11:15
  • The second duplicate link is a canonical for the actual logic error in your code. – tripleee Apr 10 '21 at 11:19

1 Answers1

0

Please try following and let me if it works for you, thanks!!

#!/bin/bash
string="##Actually Mosses##"
echo "$string"
for (( i=0; i<${#string}; i++ ));
do
        str="${string:$i:1}"
        if [[ "$str" == "#" || "$str" == " " ]]
        then
                echo -n "Yes "
        else
                echo -n "No "
        fi
done

Expected Output: ##Actually Mosses##
Yes Yes No No No No No No No No Yes No No No No No No Yes Yes

Note: Remove echo "$string" and option -n from script as it is not required in your case.

Option -n for echo is used to print on same .