aquagremlin
aquagremlin

Reputation: 3549

how to check if a word exists on a web page

In this example script below

keyword="google"
var1="wget -qO- https://www.google.com"
echo "$var1"
var2="[test -z "$var1 | grep $keyword"]"
echo $var2

I get

 wget -qO- https://www.google.com

but var2 is empty.

In this script

keyword="google"
var1="wget -qO- https://www.google.com"
echo " $var1"
var2="[test -z "https://www.google.com" | grep "google"]"
echo $var2

I get

wget -qO- https://www.google.com
[test -z https://www.google.com | grep google]

I've tried any number of permutations of single and double quotes but I cannot get the test statement to evaluate.

How can I actually get a test command to evaluate in a script? And How can I use variables in a 'test' command?

Upvotes: 0

Views: 770

Answers (1)

Jorenar
Jorenar

Reputation: 2884

Variables

var2="[test -z "$var1 | grep $keyword"]"

Let's see what is and what is not quoted here:

  • "[test -z " - first quoted atom, so far good
  • $var1 - variable gets expanded and concatenated to previous string
  • | grep $keyword - first problem, there are no quotes where are whitespaces, Bash doesn't know what to do with it (it thinks those are arguments and tries to pipe variable assignation to grep)
  • "]" - it appends it to $keyword, which is grep argument

So Bash first executes var2="[test -z "$var1 then pipes it to grep $keyword"]"

Possible solutions:

  • many quotes: var2='[test -z '"$var1"' | grep '"$keyword"']'
  • one quotes: var2="[test -z $var1 | grep $keyword]"

This is in regards of variables.

Evaluation

To evaluate text string as shell command (although you should avoid doing that at all), you simply use eval command:

eval "$var2"

or just variable alone:

"$var2"

Actual problem, i.e. checking for a word

Evaluating var2 makes no sense as the code contained inside is simply invalid. Making it a variable is needless at all.

You simply need to do:

keyword="google"
var1="wget -qO- https://www.google.com"

if test -z "$($var1 | grep $keyword)"; then
    echo "Not found word"
fi

Why was code in var2 invalid:

  • square brackets - [ is an alias for test. Writing [ test is (almost) equivalent to test test. The difference between test and [ is that in case of [ you need to end command with ]
  • no spaces after [ and before ]
  • when you want to use output of a command, you need to capture it using $(command)

Upvotes: 1

Related Questions