1

I want to use a variable as comparison operator. Is it possible? Something like:

x=10 y=20 t="<" res=`expr $x $y $t` 

or

x=10 y=20 t="-lt" if [ $x $y $t ]; then .. fi 

Whichever approach is fine by me.

0

1 Answer 1

2

Why have you not just tested* it? Yes, it is possible. Shell is interpreted language. Command test (for which [ is an alias) takes arguments just as any other command. Those can be variables as well.

Example:

#!/usr/bin/env sh x=10 y=20 t="-lt" if [ $x $t $y ]; then echo "a" fi if [ $y $t $x ]; then echo "b" else echo "c" fi t="-ge" if [ $y $t $x ]; then echo "d" fi 

Output:

a c d 

* Your example don't work, because you have operator (variable $t) after the values (variables $x and $y), not between them.

Sign up to request clarification or add additional context in comments.

1 Comment

What if I want to compare decimals?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.