Issue with `shell_command` and passing args to it

Hi, I have a shell_command that I need to pass an input_number to. Said shell_command has a pipe in it because I’m echo-ing a string that is piped into nc.

My issue is that the shell_command works fine if I have everything hard-coded. But when I replace the hard-coded value with states("input_number.my_number"), Home Assistant decides to echo everything, including the pipe character | and what’s behind it.

To illustrate simply:

configuration.yaml:

shell_command:
  my_command: echo "oh hi mark" | grep mark

The above correctly echoes “oh hi mark” then greps the result, showing “oh hi mark” as stdout if I run the command via Home Assistant > Developer Tools > Services > select my_command, and it correctly shows an empty stdout if I grep on a non-present string.

But now let’s use a variable instead:

shell_command:
  my_command: echo '{{ states("input_number.my_number") }}' | grep it_wont_work

Now if I run this via the Dev Tools, what I get as stdout is:

stdout: 15.0 | grep it_wont_work
stderr: ""
returncode: 0

That’s wrong: stdout should be the output of grep (i.e. ""), not of the whole echo line.

How can I fix this?

Thank you.

https://www.home-assistant.io/integrations/shell_command/#configuration-variables

Ah, I obviously missed that part of the doc :confused:
Is there a way around this?
Thank you.

Not that I know of.

Thanks anyway!

Using this post as inspiration:

shell_command:
  my_command:  /bin/bash -c "echo '{{ value }}' | grep test"

You could call it from the Developer tools page with:

service: shell_command.my_command
data:
  value: This is a test

and get the following response:

stdout: This is a test
stderr: ""
returncode: 0

A downside to this implementation is the Developer tools will not allow you to use templates such as:

# this does not work since templates are not supported in the UI
service: shell_command.my_command
data:
  value: >
    {{ states("input_text.text_1") }}

However, the workaround is to incorporate this into a script or automation:

script:
  my_script:
    sequence:
      - service: shell_command.my_command
        data:
          value: >
            {{ states('input_text.text_1') }}

Or, make a shell script on the file system with all your greps and whatever and call that. :slight_smile: That’s what I do.

Thanks. Let me try all that!

1 Like