0

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?

Pablo
  • 465
  • 1
  • 4
  • 14

2 Answers2

2

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • You could also use `if [[ "$string" = *$'\n'* ]]` (in bash, so be sure to fix the shebang). – Gordon Davisson Feb 01 '20 at 20:56
  • Yeah, I just find `case` less noisy. – tripleee Feb 01 '20 at 20:57
  • For more information on why the `echo` showed the linefeed as a space, see [I just assigned a variable, but echo $variable shows something else](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else/29378567) – that other guy Feb 01 '20 at 21:12
0

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
Léa Gris
  • 17,497
  • 4
  • 32
  • 41