Command line switch gives "Command failed" in log

Hi.
I have a command line switch that controls if some ovens are operating manually or automatic.
Definition of the switch:

 - platform: command_line
   switches:
     autostueovner:
       oncmd: "echo 'On' > /home/pi/.homeassistant/switch_states/autostueovner_state.txt"
       offcmd: "echo 'Off' > /home/pi/.homeassistant/switch_states/autostueovner_state.txt"
       statecmd: "/bin/grep -c 'On' /home/pi/.homeassistant/switch_states/autostueovner_state.txt"
       value_template: '{{ value == "1" }}'

The switch are acting like I want it to, but the log gets filled with messages saying that the command failed:

16-06-03 14:14:00 homeassistant.components.switch.command_line: Command failed: /bin/grep -c ‘On’ /home/pi/.homeassistant/switch_states/autostueovner_state.txt

I can’t see what is wrong. Have anyone else experienced this?

Well, first of all, txt?

edit: maybe return value ist not OK. should return 0 or 1

Return value from the command is 0 when it is Off and 1 when it is On.

Yeah, I think this evaluates the exit code of grep. Which is 1 if there in no line containing ‘On’ in the file.
You can check that by calling echo $? after runnig the grep command.
Does it show the proper state?
I think it’s 0 for on and 1 for off

Aha. So what you are saying is that it will evaluate the exit code and not the actual output of the command?

I put the “-C” after the grep command so that it will count the number of 'On’s in the file which always will be 1 if the switch is On and 0 if the switch is off.
I will try to use the exit code insred. Thanx for the tip.

1 Like

Did you ever solve this? I have the same problem running a command line sensor with grep.

Thanks,

Can you provide the configuration of your command line sensor?

I figured it out. The problem was grep returns an error code when the count of occurrences is zero. I just added the below to the sensor command, so if forces true as a result even when the count is zero.

{ grep -c XXX.XXX.XXX.XXX || true;}

Thanks,

1 Like

Thanks for posting that. Adding || true fixed my issue:

root@0f6132860925:/config# cat tvstate.sh
curl -s -H "X-CERS-DEVICE-ID: kodi" http://192.168.1.43:80/cers/api/getStatus | grep -c ExtInput || true

I use this for checking if my older Sony TV is off or on. The TV doesn’t have an API for actually checking if it is on, or off, so I just grep the status of ExtInput. If it’s 1, the TV is on. If it’s 0, or does not respond (i.e. off), then it’s 0. Adding || true has stopped the annoying log on HASS :slight_smile: