Forum Discussion

BaltoStar_12467's avatar
Mar 07, 2015

BIG-IP : iRule test that variable exists and has certain value

F5 BIG-IP Virtual Edition v11.4.1 (Build 635.0) LTM on ESXi

What is the simplest most elegant syntax to test that a variable exists and has a certain value ?

For example if I want to determine that myvariable exists and has non-zero value , is this the simplest syntax ?

when HTTP_REQUEST {
    set myvariable 0
     conditional processing ...
    set myvariable 1
     more processing ... 
    if {[info exists $myvariable] && [$myvariable]} {
     do something
    }
  • You'll need to use

    [info exists myvariable]
    (without the
    $
    ) to check for variable existence. Then you would do your other conditional check.

    So like this in your example

    when HTTP_REQUEST {
        set myvariable 0
         conditional processing ...
    
        set myvariable 1
         more processing ... 
        if {[info exists myvariable] && ($myvariable equals "1")} {
             do something
        }
    }
    

    If you know that your variable is going to be an integer, you could just use

    $myvariable
    instead of
    ($myvariable equals "1")
    as it will return a true value for any positive value.

  • Hi BaltoStar,

    if the given variable exists in 90% of the cases, then

    [catch {}]
    will do an awesome job...

    when HTTP_REQUEST {
        if { [catch {
            if { $variable } then {
                log local0.debug "The variable does exist and has a value of 1"     
            }
        }] } then {
            log local0.debug "The variable does not exists."        
        }   
    }
    

    ... but if the variable exists in less than 90% of the cases, then

    [info exists]
    will start to outperform
    [catch {}]
    .

    when HTTP_REQUEST {
        if { ( [info exists variable] )
         and ( $variable ) } then {
                log local0.debug "the variable does exist and has a value of 1"     
        } else {
            log local0.debug "The variable does not exists or has an value other than 1."       
        }
    }
    

    Note: The reson for this is that a successful

    [catch {}]
    command is slightly faster than
    [info exists]
    but on the other hand an unsuccessful
    [catch {}]
    command is much slower than
    [info exists]
    .

    Cheers, Kai