Reputation: 3549
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
Reputation: 2884
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
argumentSo Bash first executes var2="[test -z "$var1
then pipes it to grep $keyword"]"
Possible solutions:
var2='[test -z '"$var1"' | grep '"$keyword"']'
var2="[test -z $var1 | grep $keyword]"
This is in regards of variables.
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"
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:
[
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 ]
[
and before ]
$(command)
Upvotes: 1