linuxstringbashinit

Check if a string contains asterisk (*)


I want to check if my string contains one or more asterisks.

I have tried this:

if [[ $date_alarm =~ .*\*.* ]]
then
    ...
fi

It worked when I launch the script directly, but not if this script is called during shutdown (script installed in run level 0 and 6 via update-rc.d)

Any idea, suggestion?


Solution

  • Always quote strings.

    To check if the string $date_alarm contains an asterisk, you can do:

    if echo "$date_alarm" | grep '*' > /dev/null; then
        ...
    fi
    

    but it's more idiomatic to use a case statement:

    case "$date_alarm" in *\**) ...;; esac
    

    Note the quotes. Even thought the quotes really aren't necessary in the case statement (field splitting won't happen there), it is considered best practice to include them.