Devendra Rawat
Devendra Rawat

Reputation: 23

How to store a condition in a variable and evaluate it with eval?

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

Answers (2)

agc
agc

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

codeforester
codeforester

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:

  • it's important to quote your variables inside [ ] to prevent word splitting and globbing
  • use shellcheck to validate your code

See also:

Upvotes: 2

Related Questions