For Loop in command_line --> command_state

Hello, i need to iterate over a json reply and set to true only if all values are true, below the code that won’t work…

        command_state: >-
          sleep 10; StatusCams=$(curl -s -X GET http://192.168.0.23:6475/api/config); for status in $(echo $StatusCams | jq '.cameras.[].enabled'); do if [ $status == "true" ]; then echo "true"; else echo "false" && break; fi; done
        value_template: >-
          {{ value == "true" }}

The command call the API here “http://192.168.0.23:6475/api/config” and put the Json reponse in variable StatusCams the iterate with for loop and break only if find a false.
If i run this command in shell works well:

The last value is false so false should be the value evaluated and in HA i can see that the sensor is OFF, but when all cameras are true i still see that the sensor is OFF:

Seems something related to break of for loop?

I hope someone could help me :smiley:

The entire output of the command is in value, not just the last line, so

true
true
true
true
true
etc

will not equal true.

Try something like this

command_state: >-
  sleep 10; StatusCams=$(curl -s -X GET http://192.168.0.23:6475/api/config); for status in $(echo $StatusCams | jq '.cameras.[].enabled'); do if [ $status == "true" ]; then result="true"; else result="false" && break; fi; done; echo $res
1 Like

Thanks a lot for your reply :smiley:
In addition can I force this switch to follow a value of another binary sensor?

Thanks a lot
Stefano

You could create a template sensor that combines this switch and your binary sensor in any way you want.

1 Like