Reputation: 23
I am trying to store a condition for comparing values in a variable but it is not working. The code I have written is :
read op
if [ $op == "desc" ]
then
compare='${arr[0]} -gt ${arr[1]}'
if [ eval "$compare" ]
then
echo "SWAP"
fi
fi
what am I doing wrong?
Upvotes: 1
Views: 1032
Reputation: 8406
Given what the code does, eval
isn't needed and this would be enough:
read op ; [ "$op" = "desc" ] && [ "${arr[0]}" -gt "${arr[1]}" ] && echo "SWAP"
(The above is functionally equivalent to codeforester's code.)
Upvotes: 0
Reputation: 42979
The right way to write your eval
statement is:
if eval [ "$compare" ]
then
...
Don't use variables to store a command - see BashFAQ/050. You can rewrite your code as:
read op
if [ "$op" = "desc" ]; then
if [ "${arr[0]}" -gt "${arr[1]}" ]; then
echo "SWAP"
fi
fi
Notes:
[ ]
to prevent word splitting and globbingSee also:
Upvotes: 2