Command line sensor calculations in value_template

I grep some information with

    command: >-
      grep 'deleted_devices' -B 100000 /config/.storage/core.device_registry | grep -c '"fritz"'

The result is:

…which is 50 and an integer - or is it a string :question:
I want the output to be output -1 (more precisely: output = output -1). That does not work. If I do this calculation, the command_line sensor won’t be created at all:

    value_template: >-
      {% if (value | int(0) > 0) %}
        {{ value -1 }}
      {% endif %}

:x: not working

      {% if (value | int(0) > 0) %}
        {{ value == ((value | int(0)) -1) }}
      {% endif %}

:x: also not working

Only without the calculation the sensor is created (but of course with a wrong value - one too much):

    value_template: >-
      {% if (value | int(0) > 0) %}
        {{ value }}
      {% endif %}

:white_check_mark: working

How can I do this simple math calculation in the value_template section?

value_template: >
  {% if value|is_number %}
    {{ value |int -1 }}
  {% else %}
  {% endif %}
1 Like

No sir. Config check gives:

Invalid config for [sensor.command_line]: invalid template (TemplateSyntaxError: expected token 'end of statement block', got '%') for dictionary value @ data['value_template']. Got '{% if value|is_number %}\n {{ value |int -1 }}\n{% else % %}\n unavailable\n{% endif %}\n'. (See ?, line ?).

I’ll try it without the second % at the end of the else line :wink:

Update: Now it works. If you’d like to fix that typo in your post I’ll thankfully mark that as solution. :smiley:

Thank you!

Bonus question:
can you tell me why we don’t need to specify a default for the int here? Is that only necessary for template sensors? I thought that would be good (or meanwhile required) behaviour - but not sure bout those command_line sensors…

1 Like


Because this line tests if it is a number, or a string that looks like a number, that the int filter can convert:

If it does not pass that test then the int filter is skipped and the state is set to unknown.