e-raser
1
I use this:
- platform: command_line
name: HA Blocked IPs
unique_id: xxxxxxxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx
scan_interval: 60
command_timeout: 30
command: "grep -c 'banned_at:' /config/ip_bans.yaml"
value_template: >-
{% if (value | int(0) > 0) %}
{{ value }}
{% else %}
0
{% endif %}
…which works fine IF there is at least one line containing “banned_at”.
BUT if the file is empty, the sensor returns unavailable
Interestingly, running the command grep -c 'banned_at:' /config/ip_bans.yaml
directly on the CLI, this gives:
Update:
it only looked like it’s okay (output is 0 as expected). But that small little red cross gives
The file currently has this content (empty, not a single line):
How can I check for an empty file or suppress the unavailable state and default “unavailable = 0” instead?
No idea? I thought this is even too easy to ask…
msp1974
(Mark P)
3
You can do this.
grep -c 'banned_at:' /config/ip_bans.yaml || echo 0
So funny, cause that’s what I discovered - I swear - 5 seconds before your post while surfing default - How to guarantee grep returns at least one line - Stack Overflow !
Will give it a try.
Unfortunately this still does not work:
- platform: command_line
name: HA Blocked IPs
unique_id: xxxxxxxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx
scan_interval: 60
command_timeout: 30
command: "grep -c 'banned_at:' /config/ip_bans.yaml || echo 0"
value_template: >-
{% if (value | int(0) > 0) %}
{{ value }}
{% else %}
0
{% endif %}
Because when there’s no “banned_at” in the file, the response now “thanks” to the || echo 0
is now:
I have no idea how that is stored, but obviously it’s nothing {{ value }}
can easily hold…
How to work around that, probably by the value_template
?
command: "grep -c 'banned_at:' /config/ip_bans.yaml || true"
Since you still get the output you want you just need to ignore the exit code, || true
does that.
1 Like
Thanks, looks promising!
Unfortunately the cl sensor does not update (file still empty) when being reloaded using the dev-tools section button. I need to restart HA for this…
currently I have this combination (value_template
without any further tests/checks):
command: "grep -c 'banned_at:' /config/ip_bans.yaml || true"
value_template: >-
{{ value }}
Looking good for you?
1 Like