Search code examples
bashjmeterbeanshell

JMeter Beanshell Assertion: How do I save the value of Runtime.getRuntime().exec("ifconfig | grep \"${IpAddress}\" | wc -l")?


My shell command ifconfig | grep \"${IpAddress}\" | wc -l returns either 0 or 1 when run inside terminal. I need to do the same using JMeter and assert accordingly (0 is fail, 1 is pass). But when I'm doing this:

Runtime.getRuntime().exec("ifconfig | grep \"${IpAddress}\" | wc -l");

I get nothing in return! Any ideas on how I can save (and later retrieve) the value of this command's output?


Solution

    1. You're basically execute 3 commands via pipe:

      • ifconfig
      • grep
      • wc

        It will work only inside a Linux SHELL so you need to amend your command to look like:

        /bin/bash -c ifconfig | grep \"${IpAddress}\" | wc -l
        
    2. You're referring a JMeter Variable as ${IpAddress} which is not very good practice as they can resolve into something causing compilation failure. Consider using vars shorthand for JMeterVariables class instance instead like vars.get("IpAddress")

    3. You're using not the best Test Element, starting JMeter 3.1 it is recommended to use JSR223 Elements and Groovy language for any form of scripting.

    Assuming all above I would recommend using JSR223 Assertion and the code like:

    String response = org.apache.commons.lang3.StringUtils.normalizeSpace(['/bin/bash', '-c', 'ifconfig | grep \"' + vars.get('IpAddress') + '\" | wc -l'].execute().text)
    if (response.equals("1")) {
        //do what you need here
    }