Shell 命令

此集成可以将常规的 shell 命令暴露为操作。操作可以从 脚本自动化 中调用。 不允许对 shell 命令采用驼峰命名法,请仅使用小写命名,并用下划线分隔名称。

请注意,shell 命令进程将在 60 秒后终止,毫无例外。没有选项可以改变这种行为,这是设计使然,因为 Home Assistant 并不打算管理长时间运行的外部进程。

配置

# 示例 configuration.yaml 条目
# 暴露操作 shell_command.restart_pow
shell_command:
  restart_pow: touch ~/.pow/restart.txt

Configuration Variables

alias string Required

为 shell 命令提供一个名称(别名)作为变量,并在冒号后设置要执行的命令。例如,alias:你想执行的 shell 命令

命令可以是动态的,使用模板来插入参数的值。当使用模板时,shell_command 在一个更安全的环境中运行,不允许任何 shell 辅助工具,如自动展开家目录 ~ 或使用管道符号运行多个命令。类似地,只有第一个空格后的内容可以由模板生成。这意味着命令名称本身不能由模板生成,而必须字面上提供。

传入激活 shell 命令的操作数据将在模板内作为变量可用。

从命令的 stdoutstderr 输出都会被捕获,并通过将 日志级别 设置为调试来记录。

执行

command配置目录 中执行。

Tip

如果您使用 Home Assistant 操作系统,那么命令是在 homeassistant 容器上下文中执行的。所以如果您测试或调试您的脚本,最好在这个容器的上下文中进行,以获得相同的运行时环境。

0 的退出代码意味着命令成功完成且没有错误。如果命令返回非 0 的退出代码或在 60 秒超时后被终止,则结果将记录到 Home Assistant 日志中。

响应

Shell 命令提供一个响应字典,包含 stdoutstderrreturncode。这些可以用于自动化,以根据命令结果采取行动,使用 response_variable

示例

定义多个 shell 命令

您也可以一次定义多个 shell 命令。这是一个定义三个不同(无关)shell 命令的示例。

# 示例 configuration.yaml 条目
shell_command:
  restart_pow: touch ~/.pow/restart.txt
  call_remote: curl http://example.com/ping
  my_script: bash /config/shell/script.sh

自动化示例

这是一个将 shell 命令与输入助手和自动化结合使用的示例。

# 将 GUI 滑块的值应用于 shell_command
automation:
  - alias: "run_set_ac"
    triggers:
      - trigger: state
        entity_id: input_number.ac_temperature
    actions:
      - action: shell_command.set_ac_to_slider

input_number:
  ac_temperature:
    name: A/C 设置
    initial: 24
    min: 18
    max: 32
    step: 1

shell_command:
  set_ac_to_slider: 'irsend SEND_ONCE DELONGHI AC_{{ states("input_number.ac_temperature") }}_AUTO'

以下示例展示了如何在自动化中使用 shell 命令响应。

# 根据文件内容创建 ToDo 通知
automation:
  - alias: "run_get_file_contents"
    triggers:
      - ...
    actions:
      - action: shell_command.get_file_contents
        data:
          filename: "todo.txt"
        response_variable: todo_response
      - if: "{{ todo_response['returncode'] == 0 }}"
        then:
          - action: notify.mobile_app_iphone
            data:
              title: "ToDo"
              message: "{{ todo_response['stdout'] }}"
        else:
          - action: notify.mobile_app_iphone
            data:
              title: "ToDo 文件错误"
              message: "{{ todo_response['stderr'] }}"


shell_command:
  get_file_contents: "cat {{ filename }}"