Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test whether a string contains a literal asterisk

Basically looking for a string that contains an asterisk, looked all around for one that relates to an until loop but to no avail!

e.g. the user would basically keep typing in strings and the program will reject them until one that has an asterisk pops up.

then at this point it will echo a message [cant go into details sorry]

code:

until [ "string" == "[asteriskstuff]" ]
do

  echo "just give me a string with an asterisk for crying out loud"

  read "string"

done

when the user stops inputting hi and then decides to input hi* it will then show the echo message basically I just want to bypass the bleedin' asterisk because [asteriskstuff] is the area where I always falter!

all help appreciated!

SUMMARY: How can I bypass an asterisk in a simple way for an until loop?

like image 619
Student of Art Avatar asked Dec 12 '16 15:12

Student of Art


1 Answers

chepner's helpful answer explains the problem with your original approach well.

The following prompts until a literal * is found anywhere in the user input:

until [[ $string == *'*'* ]]; do
  echo "just give me a string with an asterisk, for crying out loud"
  read -r string
done
  • [[ ... ]] rather than [ ... ] must be used in order to enable pattern matching on the RHS of == (=).

    • Unless you're writing POSIX-compliant scripts (for /bin/sh), where only [ ... ] is supported, consider using [[ ... ]] routinely, because it offers more features and fewer surprises: see this answer of mine.
  • *'*'* is a pattern that says: match a literal * - the single-quoted part - anywhere in the string; the unquoted * instances represent any run of characters.

    • These patterns are the same as the ones used in filename globbing and are not regular expressions.
    • However, Bash also offers regular expression matching, via [[ ... =~ ... ]]. Thus, the conditional could also be written as [[ $string =~ '*' ]] or [[ $string =~ \* ]]
  • -r should be used with read as a matter of habit, to prevent unexpected processing of \ chars.

like image 152
mklement0 Avatar answered Nov 12 '22 00:11

mklement0