I am trying to find out if a hostname has a domain suffix by searching for a period in the string. I can do it in bash
with the following
#!/bin/bash
if [[ "$1" =~ \. ]]; then
host="$1"
echo "keep as $host"
else
host="$1.mydomain.biz"
echo "change to $host"
fi
but it doesn't work for zsh
. The [[ "$1" =~ \. ]]
always evaluates to True:
#!/bin/zsh
if [[ "$1" =~ \. ]]; then
# always evaluates to True in zsh
host="$1"
echo "keep as $host"
else
host="$1.mydomain.biz"
echo "change to $host"
fi
Eventually something like this will go in my .zshrc
, but experimenting with it as a shell file gave me insight.
How should I update the regex evaluation to get this to work in zsh
? Or is there a different test I can use to determine if I need to add the domain suffix?
My environment is macOS Sonoma 14.2.1, zsh 5.9 (x86_64-apple-darwin23.0)
There fix is that you need to double escape the dot here:
if [[ "$1" =~ \\. ]]; then
Then the backslash will be treated as a regular, literal backslash that escapes a dot in the regex pattern.
Else, you may simply use
if [[ "$1" == *.* ]]; then
where *
stands for any text (it is required because ==
requires an exact match, full string match), but that is no longer a regex.