How to check if a bash variable contains an asterik?

Handling asterikes (*) in bash variables can be annoying. To check if a variable in bash contains an asterisk, you can use the double square brackets and the wildcard pattern matching feature. That's how you can do it:

#!/bin/bash

var="hello*world"

if [[ "$var" == *"*"* ]]; then
echo "The variable contains an asterisk."
else
echo "The variable does not contain an asterisk."
fi

Asterik at the beginning of the string #

Unfortunately, this doesn't cover the edge case of an asterisk at the start of a string. So any string such as *.releasecandidate.dev to match any sub-domains wouldn't be covered. To handle this case, you can use the case statement with a pattern that starts with an asterisk:

#!/bin/bash

var="*hello world"

case "$var" in
*"*"*)
echo "The variable contains an asterisk."
;;
*)
echo "The variable does not contain an asterisk."
;;
esac

Here we use a case statement with a pattern that starts with an asterisk (*"*"*). This pattern matches any string that contains an asterisk, regardless of its position within the string. If the pattern is matched, then we print out that the variable contains an asterisk. If not, then we print out that the variable does not contain an asterisk. You can tweak this to your needs.

Wrapping it in function returning a boolean #

We can modify the function to return a boolean instead of printing a text message to make it more useable:

#!/bin/bash

function has_asterisk {
case "$1" in
*"*"*)
return 0 # return true if the variable contains an asterisk
;;
*)
return 1 # return false if the variable does not contain an asterisk
;;
esac
}

# example usage
var1="hello world"
var2="*ello world"

if has_asterisk "$var1"; then
echo "The variable '$var1' contains an asterisk."
else
echo "The variable '$var1' does not contain an asterisk."
fi

if has_asterisk "$var2"; then
echo "The variable '$var2' contains an asterisk."
else
echo "The variable '$var2' does not contain an asterisk."
fi

The output will be:

The variable 'hello world' does not contain an asterisk.
The variable '*ello world' contains an asterisk.

🙏🙏🙏

Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated 💖! For feedback, please ping me on Twitter.

Published