0

Is it possible to set comparison sign as variable?

I want to do something like that:

var1=${1} var2=${2} condition=${3} if [[ "${var1}" "${condition}" "${var2}" ]]; then echo "Warning!" fi 
./alert.sh "10" "5" ">" 
2
  • 1
    You could replace [[ with eval [[. Commented Jun 6, 2021 at 17:03
  • 2
    You could also shoot yourself in the foot; neither is probably something you want to do, though. eval will evaluate whatever string it gets, rather than just the parts you "expect" to be evaluated. Commented Jun 6, 2021 at 17:04

2 Answers 2

5

Setting it is no problem, it's using it that's difficult. (Your code raises a syntax error.)

You could switch from [[ ]] to test, though it's not exactly the same.

By the way, > is a string operator. You probably wanted -gt, the integer operator. See the link above for a table of operators.

var1="10" var2="5" condition="-gt" if test "${var1}" "${condition}" "${var2}"; then echo "Warning!" fi 

Output:

Warning! 

Single square brackets also work (they're equivalent), but for some reason, ShellCheck detects a syntax error, so to make life easier with ShellCheck, I'd say just avoid it, even if that's a bug.

[ "${var1}" "${condition}" "${var2}" ] 
Sign up to request clarification or add additional context in comments.

Comments

-1

An other way of doing such work is to construct & launch a second script.

It should be easier to debug (you can see & redo directly the cde)

echo " #!/bin/bash echo "es2 Start" ... write your cdes here ... with parameters you want 

" > es2

chmod +x es2 ./es2 

4 Comments

Your quoting is wrong, even ignoring the possibility of the variables themselves containing quotes in their values.
It's just an example you can do what you want ... of course not if you want to copy / paste :-) Hope other people will find the tip useful...
People needing a tip like this will need to be made aware of the pitfalls of this approach, something you did not address.
That's precisely why this approach is useful, people can see the real cde (and debug) via the second file ... so I rewrite my answer without "real code"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.