Pablo
Pablo

Reputation: 515

The space is not detected in string

I use dig to find the IP of a subdomain and assign it to a variable called string. This subdomain has 2 IPs and the IPs are separated by space. I want to say that if there is a space in the string, announce it. I use this code:

#!/bin/bash
string=$(dig +short google.com)
echo $string
if [[ "$string" =~ \ |\' ]]    #  slightly more readable: if [[ "$string" =~>
then
   echo "Matches"
else
   echo "No matches"
fi

Although there is a space in "string", it says "no matches". I also tried newline character (\n), it wasn't detected as well. What's wrong?

Upvotes: 0

Views: 74

Answers (2)

Léa Gris
Léa Gris

Reputation: 19625

You would probably be better with host rather than dig as the former provides a shell return code to indicate success or failure:

if host example.com >/dev/null
then
   echo "Matches"
else
   echo "No matches"
fi

Upvotes: 0

tripleee
tripleee

Reputation: 189679

The entries are separated by a newline. You should get used to quote the strings you echo.

case $string in
  *$'\n'*) echo "Matches";;
  *) echo "No matches";;
esac

Diagnostic messages should perhaps go to standard error (add a redirect to >&2).

Also, the # in the shebang line is significant; the first two bytes of the file need to be exactly #! in order for this construct to work.

Upvotes: 2

Related Questions