Search code examples
stringshellswitch-statementash

Ash script - detect whether a variable equals to "?"


I am writing an Ash script and trying to detect whether an input variable equals to "?" or not. I found out that it is best to use case for doing this, but I can't manage to get this working. My code is:

case $@ in
*?*) usage
    operationSucceeded
    exit;;
  *) echo "Unknown argument: $@"
    usage
    operationFailed
    exit $E_OPTERROR;;   # DEFAULT\
esac

The first option always gets triggered, while I want it to trigger only when ? is the variable, and the other option for everything else.


Solution

  • change to

     case $@ in
         *[\?]* ) usage 
        .....
      easc
    

    You may not need the '\' , but it can't hurt.

    In the more general sense, [ABC] is called a character class, and will match any of the single chars listed inside [ ]. So in *[\?]*, we're saying "any number of characters (including zero chars), followed by the Char class [\?] (in this case, only the '?' char), followed by zero or more characters".

    IHTH