> ## Documentation Index
> Fetch the complete documentation index at: https://extended-openai-conversation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Bash Functions

> Execute shell commands with security controls

Bash functions execute shell commands with built-in security controls, allowing AI assistants to interact with the operating system, run scripts, and perform system operations.

<Warning>
  **Security Considerations**

  Bash functions execute arbitrary shell commands. They include multiple layers of security:

  * Command deny patterns (e.g., `rm -rf`, `format`, destructive operations)
  * Workspace restriction (limits file access to designated directories)
  * Command allowlist patterns (optional whitelist)
  * Timeout protection (default: 300 seconds)
  * Output size limits (10,000 characters)

  Always review generated commands before enabling bash functions.
</Warning>

## Configuration

```yaml theme={null}
function:
  type: bash
  command: "{{ your_command_here }}"
```

<ParamField path="command" type="template" required>
  Shell command to execute. Can include Jinja2 templates for dynamic parameters.
</ParamField>

<ParamField path="cwd" type="template">
  Working directory for command execution. Defaults to `config/extended_openai_conversation/`.
</ParamField>

<ParamField path="restrict_to_workspace" type="boolean" default="true">
  When `true`, restricts file operations to the working directory and blocks path traversal. Set to `false` to allow access outside the workspace (use with caution).
</ParamField>

<ParamField path="allow_patterns" type="array">
  Optional list of regex patterns. If provided, commands must match at least one pattern to execute.
</ParamField>

## Examples

### Execute Bash Command

```yaml theme={null}
- spec:
    name: bash
    description: Execute a bash command in workspace.
    parameters:
      type: object
      properties:
        command:
          type: string
          description: Bash command to execute
      required:
      - command
  function:
    type: bash
    command: '{{command}}'
```

### Custom Working Directory

Execute commands in a specific directory. The `cwd` parameter sets the working directory for command execution.

```yaml theme={null}
- spec:
    name: bash_with_cwd
    description: Execute a bash command in a specific directory.
    parameters:
      type: object
      properties:
        command:
          type: string
          description: Bash command to execute
      required:
      - command
  function:
    type: bash
    command: '{{command}}'
    cwd: "/config/www/custom-panel"
```

### Unrestricted Access (Outside Workspace)

Allow access outside the workspace directory. Setting `restrict_to_workspace: false` removes path restrictions.

<Warning>
  This allows commands to access any path on the system. Use only for trusted operations.
</Warning>

```yaml theme={null}
- spec:
    name: bash_unrestricted
    description: Execute a bash command with unrestricted filesystem access.
    parameters:
      type: object
      properties:
        command:
          type: string
          description: Bash command to execute
      required:
      - command
  function:
    type: bash
    command: '{{command}}'
    restrict_to_workspace: false
```

### Command Allowlist

Restrict to specific command patterns for additional security. The `allow_patterns` parameter only allows commands matching the specified regex patterns.

```yaml theme={null}
- spec:
    name: bash_restricted
    description: Execute a bash command restricted to specific patterns.
    parameters:
      type: object
      properties:
        command:
          type: string
          description: Bash command to execute
      required:
      - command
  function:
    type: bash
    command: '{{command}}'
    allow_patterns:
      - "^git\\s+"
      - "^ls\\s+"
```

## Return Value

Bash functions return an object with command execution results:

```json theme={null}
{
  "exit_code": 0,
  "stdout": "command output here",
  "stderr": "error output (if any)"
}
```

* `exit_code`: Command exit status (0 = success, non-zero = error)
* `stdout`: Standard output from the command
* `stderr`: Error output (only included if present)

### Error Handling

If the command is blocked by security controls:

```json theme={null}
{
  "error": "Command blocked by security policy: matches pattern '...'"
}
```

If the command times out:

```json theme={null}
{
  "error": "Command timed out after 300 seconds"
}
```

## Security Features

<AccordionGroup>
  <Accordion title="Deny Patterns">
    Commands matching these patterns are automatically blocked:

    * `rm\s+-rf` - Recursive force delete
    * `format` - Disk formatting
    * `mkfs` - Filesystem creation
    * `dd\s+if=` - Low-level disk operations
    * `:(){:|:&};:` - Fork bombs
    * And more destructive patterns

    See `SHELL_DENY_PATTERNS` in the source code for the complete list.
  </Accordion>

  <Accordion title="Path Traversal Protection">
    When `restrict_to_workspace: true` (default):

    * Blocks `../` and `..\` patterns
    * Validates working directory is within allowed directories
    * Extracts and validates all paths in the command
    * Ensures paths don't escape the workspace
  </Accordion>

  <Accordion title="Timeout Protection">
    Commands are terminated after timeout (default: 300 seconds):

    ```yaml theme={null}
    # Pass timeout in parameters
    parameters:
      type: object
      properties:
        timeout:
          type: number
          description: Timeout in seconds
    ```
  </Accordion>

  <Accordion title="Output Limits">
    Output is truncated if it exceeds 10,000 characters to prevent memory issues.
  </Accordion>
</AccordionGroup>

## Use Cases

<CardGroup cols={2}>
  <Card title="System Monitoring" icon="monitor">
    Check disk usage, memory, processes, and system health
  </Card>

  <Card title="File Management" icon="folder">
    List, search, and organize files in the workspace
  </Card>

  <Card title="Backup Operations" icon="floppy-disk">
    Run backup scripts and verify backups
  </Card>

  <Card title="Git Operations" icon="code-branch">
    Check repository status, view logs, manage configs
  </Card>

  <Card title="Network Diagnostics" icon="network-wired">
    Ping hosts, check connectivity, view network status
  </Card>

  <Card title="Custom Scripts" icon="file-code">
    Execute maintenance scripts and automation tools
  </Card>
</CardGroup>

## Best Practices

<Steps>
  <Step title="Start with workspace restriction">
    Always use `restrict_to_workspace: true` (default) unless you specifically need broader access. This prevents accidental access to sensitive system files.
  </Step>

  <Step title="Use allowlist patterns for sensitive operations">
    When functions could be misused, add `allow_patterns` to restrict commands:

    ```yaml theme={null}
    allow_patterns:
      - "^git\\s+"    # Only allow git commands
      - "^ls\\s+"     # Only allow ls commands
    ```
  </Step>

  <Step title="Handle errors gracefully">
    Check the return value and handle non-zero exit codes:

    ```yaml theme={null}
    # Use composite function to check exit code
    type: composite
    sequence:
      - type: bash
        command: "{{ command }}"
        response_variable: result
      - type: template
        value_template: >-
          {% if result.exit_code == 0 %}
            Success: {{ result.stdout }}
          {% else %}
            Error (exit {{ result.exit_code }}): {{ result.stderr }}
          {% endif %}
    ```
  </Step>

  <Step title="Set appropriate timeouts">
    For long-running operations, pass a custom timeout:

    ```yaml theme={null}
    # Let AI specify timeout in parameters
    parameters:
      properties:
        timeout:
          type: number
          default: 300
    ```
  </Step>

  <Step title="Sanitize user inputs">
    Always sanitize inputs to prevent command injection:

    ```yaml theme={null}
    # BAD - vulnerable to injection
    command: "echo {{ user_input }}"

    # BETTER - quote the variable
    command: "echo '{{ user_input }}'"
    ```
  </Step>
</Steps>

## Common Patterns

### Check if File Exists

```yaml theme={null}
- spec:
    name: file_exists
    description: Check if a file exists
    parameters:
      type: object
      properties:
        filename:
          type: string
  function:
    type: bash
    command: "test -f '{{ filename }}' && echo 'exists' || echo 'not found'"
```

### Search Files by Content

```yaml theme={null}
- spec:
    name: search_files
    description: Search for text in files
    parameters:
      type: object
      properties:
        search_term:
          type: string
        path:
          type: string
          default: "."
  function:
    type: bash
    command: "grep -r '{{ search_term }}' {{ path }}"
```

### Get File Count

```yaml theme={null}
- spec:
    name: count_files
    description: Count files in directory
    parameters:
      type: object
      properties:
        pattern:
          type: string
          description: File pattern (e.g., "*.yaml")
  function:
    type: bash
    command: "find . -name '{{ pattern }}' | wc -l"
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Command blocked by security policy">
    Your command matches a deny pattern. Review `SHELL_DENY_PATTERNS` in the code. If the command is safe, consider using a different approach or contact the maintainers to update the patterns.
  </Accordion>

  <Accordion title="Path outside working directory">
    The command tries to access files outside the workspace. Either:

    * Adjust paths to be within the workspace
    * Set `restrict_to_workspace: false` (use with caution)
    * Add custom `allow_dir` in file functions
  </Accordion>

  <Accordion title="Command not in allowlist">
    When `allow_patterns` is set, commands must match at least one pattern. Check your regex patterns or adjust the command.
  </Accordion>

  <Accordion title="Command timeout">
    Long-running commands may timeout. Pass a custom `timeout` parameter or optimize the command.
  </Accordion>
</AccordionGroup>

## FAQ

<AccordionGroup>
  <Accordion title="Can bash functions modify system files?">
    Yes, if `restrict_to_workspace: false`. By default, modifications are limited to the workspace directory (`config/extended_openai_conversation/`).
  </Accordion>

  <Accordion title="Are environment variables available?">
    Yes. Commands run in a shell environment with access to environment variables. The working directory persists between commands in a session.
  </Accordion>

  <Accordion title="Can I run interactive commands?">
    No. Commands must complete without user interaction. Interactive commands (like `vim`, `top -i`) will fail or timeout.
  </Accordion>

  <Accordion title="How do I debug command failures?">
    Enable debug logging:

    ```yaml theme={null}
    logger:
      logs:
        custom_components.extended_openai_conversation: debug
    ```

    This will log all executed commands and their output.
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={3}>
  <Card title="File Functions" icon="file" href="/functions/read_file">
    Read, write, and edit files safely
  </Card>

  <Card title="Composite Functions" icon="layer-group" href="/functions/composite">
    Combine bash with other functions
  </Card>

  <Card title="Script Functions" icon="scroll" href="/functions/script">
    Use Home Assistant scripts instead
  </Card>
</CardGroup>
