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)