0

I have problem with this script

The Output is always "Your string has been found" even if there isn't anything in /etc/hosts. Do you have any ideas how to solve this problem or is it even possible to do this?

Any feedback is appreciated. I'm beginning to learn bash so feel free to critize me.

Thank you.

#!/bin/bash

google= dig +noall +answer www.google.com | awk '{ print $1, $NF }' 
hosts= cat /etc/hosts | grep "www.google.com" 

if [ $google == $hosts ] ; then
    echo "Your string has been found"
else
    echo "Your string has not been found"
fi

Rav
  • 3
  • 1
  • [There shouldn't be a space after the assignment `=`](https://stackoverflow.com/questions/2268104/command-not-found-error-in-bash-variable-assignment) – 0stone0 May 20 '21 at 14:37
  • You aren't setting the variables `google` and `hosts`; you are missing the command substitutions to capture the output of the two pipes. – chepner May 20 '21 at 14:38
  • Also, to assign the result of a command to a variable, you'll need [`$()`](https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash) – 0stone0 May 20 '21 at 14:38
  • `google` and `hosts` are both empty, and you aren't quoting their expansions, so all you are testing is if `==` is a non-empty string, which it is. – chepner May 20 '21 at 14:38
  • Reason your test is always true is simple - both strings are empty, therefore `[ "$google" = "$hosts" ]` is always true. First you should use command substitution with `$()` or `\`\``, : `google=$(dig +noall +answer www.google.com | awk '{ print $1, $NF }')`, `hosts=$(cat /etc/hosts | grep "www.google.com")` without spaces in between and then you can start going further. – tansy May 21 '21 at 14:57

0 Answers0