> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/home-assistant/core/llms.txt
> Use this file to discover all available pages before exploring further.

# Scripts

> Understanding scripts in Home Assistant Core

Scripts are reusable sequences of actions that can be called from automations, scenes, or manually triggered. They provide a way to organize and reuse complex action sequences.

## What is a Script?

A script is a named sequence of actions that can be executed on demand. Unlike automations, scripts don't have triggers - they must be explicitly called via a service call.

<CodeGroup>
  ```yaml Example Script theme={null}
  script:
    morning_routine:
      alias: "Morning Routine"
      description: "Turn on lights and start coffee maker"
      sequence:
        - service: light.turn_on
          target:
            entity_id: light.bedroom
          data:
            brightness: 128
        - delay: "00:00:30"
        - service: switch.turn_on
          target:
            entity_id: switch.coffee_maker
  ```
</CodeGroup>

## Script Structure

Scripts are entities with the domain `script` and are implemented in `homeassistant/components/script/`.

### Script Entity

Each script is represented as an entity that extends `ToggleEntity` and `RestoreEntity`:

<CodeGroup>
  ```python homeassistant/components/script/__init__.py:1-50 theme={null}
  """Support for scripts."""

  from homeassistant.helpers.entity import ToggleEntity
  from homeassistant.helpers.entity_component import EntityComponent
  from homeassistant.helpers.restore_state import RestoreEntity

  class BaseScriptEntity(ToggleEntity, RestoreEntity, ABC):
      """Base class for script entities."""
  ```
</CodeGroup>

### Key Properties

* `entity_id`: Format is `script.<script_name>`
* `state`: Either "on" (running) or "off" (not running)
* `last_triggered`: Timestamp of last execution
* `mode`: Execution mode (single, restart, queued, parallel)
* `current`: Number of currently running executions
* `max`: Maximum number of parallel/queued executions

## Script Definition

Scripts are defined with the following structure:

```yaml theme={null}
script:
  script_name:
    alias: "Human-readable name"
    description: "What this script does"
    icon: "mdi:script"
    mode: single  # Execution mode
    max: 10  # Max parallel/queued runs
    fields:
      # Input parameters
      brightness:
        description: "Light brightness"
        example: 128
    variables:
      # Script variables
      delay_time: "00:00:30"
    sequence:
      # Actions to perform
      - service: light.turn_on
        data:
          brightness: "{{ brightness }}"
```

## Execution Modes

Scripts support different execution modes when called while already running:

| Mode       | Behavior                                 |
| ---------- | ---------------------------------------- |
| `single`   | Ignore new calls while running (default) |
| `restart`  | Stop current run and start new one       |
| `queued`   | Queue new runs to execute sequentially   |
| `parallel` | Run multiple instances in parallel       |

<CodeGroup>
  ```yaml Mode Examples theme={null}
  script:
    single_mode:
      mode: single
      sequence:
        - delay: "00:01:00"
    
    restart_mode:
      mode: restart
      sequence:
        - delay: "00:01:00"
    
    queued_mode:
      mode: queued
      max: 5  # Maximum 5 queued runs
      sequence:
        - delay: "00:01:00"
    
    parallel_mode:
      mode: parallel
      max: 10  # Maximum 10 parallel runs
      sequence:
        - delay: "00:01:00"
  ```
</CodeGroup>

## Script Fields

Scripts can accept input parameters through fields:

```yaml theme={null}
script:
  set_light:
    fields:
      entity_id:
        description: "The light entity to control"
        example: "light.living_room"
        required: true
        selector:
          entity:
            domain: light
      brightness:
        description: "Brightness value"
        example: 128
        selector:
          number:
            min: 0
            max: 255
      color:
        description: "RGB color"
        example: "[255, 0, 0]"
    sequence:
      - service: light.turn_on
        target:
          entity_id: "{{ entity_id }}"
        data:
          brightness: "{{ brightness }}"
          rgb_color: "{{ color }}"
```

## Variables

Scripts can define variables for use throughout the sequence:

```yaml theme={null}
script:
  notify_with_delay:
    variables:
      notification_delay: "00:00:05"
      notification_title: "Home Assistant"
    sequence:
      - delay: "{{ notification_delay }}"
      - service: notify.notify
        data:
          title: "{{ notification_title }}"
          message: "Script executed"
```

## Calling Scripts

### From YAML

```yaml theme={null}
# Call a script without parameters
service: script.morning_routine

# Call a script with parameters
service: script.set_light
data:
  entity_id: light.living_room
  brightness: 200
  color: [255, 0, 0]

# Turn on/off (same as calling)
service: script.turn_on
target:
  entity_id: script.morning_routine
data:
  variables:
    custom_var: value
```

### From Python

<CodeGroup>
  ```python Call Script theme={null}
  from homeassistant.components import script

  # Check if script is running
  is_running = script.is_on(hass, "script.morning_routine")

  # Call script service
  await hass.services.async_call(
      "script",
      "morning_routine",
      {},
      blocking=True,
  )

  # Turn on script with variables
  await hass.services.async_call(
      "script",
      "turn_on",
      {
          "entity_id": "script.set_light",
          "variables": {
              "brightness": 200,
          },
      },
  )
  ```
</CodeGroup>

## Script Actions

Scripts support all the same actions as automations:

### Service Calls

```yaml theme={null}
sequence:
  - service: light.turn_on
    target:
      entity_id: light.living_room
    data:
      brightness: 255
```

### Delays

```yaml theme={null}
sequence:
  - delay: "00:00:30"  # Fixed delay
  - delay:
      seconds: "{{ delay_seconds }}"  # Template delay
```

### Waits

```yaml theme={null}
sequence:
  # Wait for condition
  - wait_template: "{{ is_state('binary_sensor.motion', 'off') }}"
    timeout: "00:05:00"
  
  # Wait for trigger
  - wait_for_trigger:
      - platform: state
        entity_id: binary_sensor.motion
        to: "off"
    timeout: "00:05:00"
```

### Conditional Execution

```yaml theme={null}
sequence:
  - choose:
      - conditions:
          - condition: state
            entity_id: sun.sun
            state: "below_horizon"
        sequence:
          - service: light.turn_on
            data:
              brightness: 255
      - conditions:
          - condition: state
            entity_id: sun.sun
            state: "above_horizon"
        sequence:
          - service: light.turn_on
            data:
              brightness: 128
    default:
      - service: light.turn_off
```

### Repeat Actions

```yaml theme={null}
sequence:
  # Repeat count
  - repeat:
      count: 3
      sequence:
        - service: light.toggle
          target:
            entity_id: light.living_room
        - delay: "00:00:01"
  
  # Repeat while
  - repeat:
      while:
        - condition: state
          entity_id: binary_sensor.motion
          state: "on"
      sequence:
        - service: light.turn_on
        - delay: "00:01:00"
  
  # Repeat until
  - repeat:
      until:
        - condition: state
          entity_id: binary_sensor.motion
          state: "off"
      sequence:
        - delay: "00:00:10"
```

## Script Management

### Services

```yaml theme={null}
# Turn on (run) script
service: script.turn_on
target:
  entity_id: script.morning_routine

# Turn off (stop) script
service: script.turn_off
target:
  entity_id: script.morning_routine

# Toggle script
service: script.toggle
target:
  entity_id: script.morning_routine

# Reload scripts
service: script.reload
```

## Helper Functions

The script component provides helper functions:

<CodeGroup>
  ```python homeassistant/components/script/__init__.py:130-187 theme={null}
  @callback
  def scripts_with_entity(hass: HomeAssistant, entity_id: str) -> list[str]:
      """Return all scripts that reference the entity."""
      return _scripts_with_x(hass, entity_id, "referenced_entities")

  @callback
  def scripts_with_device(hass: HomeAssistant, device_id: str) -> list[str]:
      """Return all scripts that reference the device."""
      return _scripts_with_x(hass, device_id, "referenced_devices")

  @callback
  def scripts_with_area(hass: HomeAssistant, area_id: str) -> list[str]:
      """Return all scripts that reference the area."""
      return _scripts_with_x(hass, area_id, "referenced_areas")

  @callback
  def scripts_with_blueprint(hass: HomeAssistant, blueprint_path: str) -> list[str]:
      """Return all scripts that reference the blueprint."""
  ```
</CodeGroup>

## Tracing

Scripts support execution tracing for debugging:

```yaml theme={null}
script:
  debug_example:
    trace:
      stored_traces: 10  # Number of traces to keep
    sequence:
      - service: light.turn_on
      - delay: "00:00:01"
      - service: light.turn_off
```

Traces provide:

* Execution timeline
* Variable values at each step
* Action results
* Execution duration

## Blueprints

Scripts can use blueprints for reusability:

```yaml theme={null}
blueprint:
  name: Notification Script
  description: Send a notification with custom message
  domain: script
  input:
    notify_service:
      name: Notification Service
      selector:
        text:
    message:
      name: Message
      selector:
        text:

sequence:
  - service: "notify.{{ notify_service }}"
    data:
      message: "{{ message }}"
```

## Response Data

Scripts can return response data:

```yaml theme={null}
script:
  calculate_value:
    sequence:
      - stop: ""
        response_variable: result
        data:
          value: "{{ 1 + 1 }}"
```

Call with response:

```yaml theme={null}
action:
  - service: script.calculate_value
    response_variable: my_result
  - service: notify.notify
    data:
      message: "Result: {{ my_result.value }}"
```

## Best Practices

<Card title="Descriptive Names" icon="tag">
  Use clear aliases and descriptions for better maintainability.
</Card>

<Card title="Parameterization" icon="sliders">
  Use fields to make scripts reusable with different parameters.
</Card>

<Card title="Proper Mode" icon="play">
  Choose execution modes that match your script's behavior.
</Card>

<Card title="Error Handling" icon="triangle-exclamation">
  Use conditions and choose blocks to handle different scenarios.
</Card>

<Card title="Documentation" icon="book">
  Include descriptions for fields to help users understand parameters.
</Card>

## Events

Script execution fires events:

```python theme={null}
EVENT_SCRIPT_STARTED = "script_started"
```

Event data includes:

* `entity_id`: The script entity
* `name`: Script name
* `variables`: Variables passed to script

## Common Patterns

### Notification Script

```yaml theme={null}
script:
  notify_all:
    fields:
      title:
        description: "Notification title"
      message:
        description: "Notification message"
    sequence:
      - service: notify.mobile_app
        data:
          title: "{{ title }}"
          message: "{{ message }}"
      - service: notify.tv
        data:
          message: "{{ title }}: {{ message }}"
```

### Device Control

```yaml theme={null}
script:
  control_lights:
    fields:
      room:
        selector:
          entity:
            domain: light
      action:
        selector:
          select:
            options:
              - turn_on
              - turn_off
              - toggle
    sequence:
      - service: "light.{{ action }}"
        target:
          entity_id: "{{ room }}"
```

## Related Resources

<CardGroup cols={2}>
  <Card title="Automations" icon="wand-magic-sparkles" href="/concepts/automations">
    Learn how scripts integrate with automations
  </Card>

  <Card title="Scenes" icon="image" href="/concepts/scenes">
    Understand scene activation patterns
  </Card>

  <Card title="Service Calls" icon="tower-broadcast" href="/architecture/services">
    Explore the service call system
  </Card>

  <Card title="Templates" icon="code" href="/topics/templating">
    Master templating in scripts
  </Card>
</CardGroup>
