> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Running

> Execute shell commands synchronously in HopX sandboxes. Run shell commands for system administration, package installation, file operations, and automation tasks. Learn how to execute commands, capture output, handle errors, and process command results using Python and JavaScript SDKs or REST API. Includes examples for common use cases.

Run shell commands synchronously in your sandbox. Commands execute and return results immediately, making them perfect for quick operations, package installation, and system tasks.

## Overview

Synchronous command execution is ideal for:

* Quick shell commands and system operations
* Package installation (pip, npm, apt, etc.)
* File system operations
* Environment setup and configuration
* Commands that complete in seconds or minutes

<Note>
  Commands run in `/bin/sh` by default. For commands that complete quickly, synchronous execution is simpler than background execution.
</Note>

## Basic Command Execution

Run a simple shell command:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Run a simple command
    result = sandbox.commands.run('ls -la /workspace')
    print(result.stdout)
    print(f"Exit code: {result.exit_code}")

    sandbox.kill()
    ```

    **Expected Output:**

    ```
    total 8
    drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
    drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
    Exit code: 0
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Run a simple command
    const result = await sandbox.commands.run('ls -la /workspace');
    console.log(result.stdout);
    console.log(`Exit code: ${result.exitCode}`);

    await sandbox.kill();
    ```

    **Expected Output:**

    ```
    total 8
    drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
    drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
    Exit code: 0
    ```
  </Tab>
</Tabs>

## Command Result

The `CommandResult` object contains:

* **`stdout`** - Standard output from command
* **`stderr`** - Standard error output (if any)
* **`exit_code`** - Exit code (0 = success, non-zero = error)
* **`success`** - Boolean indicating if command succeeded
* **`execution_time`** - Time taken in seconds

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    result = sandbox.commands.run('echo "Hello, World!"')

    # Access all result fields
    print(f"Output: {result.stdout}")
    print(f"Errors: {result.stderr}")
    print(f"Success: {result.success}")
    print(f"Exit code: {result.exit_code}")
    print(f"Execution time: {result.execution_time}s")

    sandbox.kill()
    ```

    **Expected Output:**

    ```
    Output: Hello, World!
    Errors: 
    Success: True
    Exit code: 0
    Execution time: 0.15s
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    const result = await sandbox.commands.run('echo "Hello, World!"');

    // Access all result fields
    console.log(`Output: ${result.stdout}`);
    console.log(`Errors: ${result.stderr}`);
    console.log(`Success: ${result.success}`);
    console.log(`Exit code: ${result.exitCode}`);
    console.log(`Execution time: ${result.executionTime}s`);

    await sandbox.kill();
    ```

    **Expected Output:**

    ```
    Output: Hello, World!
    Errors: 
    Success: true
    Exit code: 0
    Execution time: 0.15
    ```
  </Tab>
</Tabs>

## Package Installation

Install packages using package managers:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Install Python packages
    result = sandbox.commands.run('pip install requests pandas numpy', timeout=300)
    if result.success:
        print("Packages installed successfully")
        print(result.stdout)
    else:
        print(f"Installation failed: {result.stderr}")

    # Install Node.js packages
    result = sandbox.commands.run('npm install express lodash', timeout=300)
    print(f"npm install exit code: {result.exit_code}")

    sandbox.kill()
    ```

    **Expected Output:**

    ```
    Packages installed successfully
    Successfully installed requests-2.31.0 pandas-2.1.0 numpy-1.24.3
    npm install exit code: 0
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Install Python packages
    const result = await sandbox.commands.run('pip install requests pandas numpy', {
      timeout: 300
    });
    if (result.success) {
      console.log('Packages installed successfully');
      console.log(result.stdout);
    } else {
      console.error(`Installation failed: ${result.stderr}`);
    }

    // Install Node.js packages
    const npmResult = await sandbox.commands.run('npm install express lodash', {
      timeout: 300
    });
    console.log(`npm install exit code: ${npmResult.exitCode}`);

    await sandbox.kill();
    ```

    **Expected Output:**

    ```
    Packages installed successfully
    Successfully installed requests-2.31.0 pandas-2.1.0 numpy-1.24.3
    npm install exit code: 0
    ```
  </Tab>
</Tabs>

## Environment Variables

Pass environment variables to commands:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Run command with environment variables
    result = sandbox.commands.run(
        'echo $API_KEY',
        env={"API_KEY": "sk-123", "DEBUG": "true"}
    )
    print(result.stdout)  # "sk-123"

    # Use environment variables in commands
    result = sandbox.commands.run(
        'python -c "import os; print(os.getenv(\'API_KEY\'))"',
        env={"API_KEY": "sk-456"}
    )
    print(result.stdout)  # "sk-456"

    sandbox.kill()
    ```

    **Expected Output:**

    ```
    sk-123
    sk-456
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Run command with environment variables
    const result = await sandbox.commands.run('echo $API_KEY', {
      env: { API_KEY: 'sk-123', DEBUG: 'true' }
    });
    console.log(result.stdout);  // "sk-123"

    // Use environment variables in commands
    const pythonResult = await sandbox.commands.run(
      'python -c "import os; print(os.getenv(\'API_KEY\'))"',
      { env: { API_KEY: 'sk-456' } }
    );
    console.log(pythonResult.stdout);  // "sk-456"

    await sandbox.kill();
    ```

    **Expected Output:**

    ```
    sk-123
    sk-456
    ```
  </Tab>
</Tabs>

<Note>
  Environment variables passed to `commands.run()` have priority over global environment variables set via `sandbox.env.set()`. Priority: Request env > Global env > Agent env.
</Note>

## Working Directory

Specify a custom working directory:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Create directory
    sandbox.files.mkdir('/workspace/myproject')

    # Run command in specific directory
    result = sandbox.commands.run(
        'pwd',
        working_dir='/workspace/myproject'
    )
    print(result.stdout)  # "/workspace/myproject"

    # Run multiple commands in same directory
    result = sandbox.commands.run(
        'touch file.txt && ls -la',
        working_dir='/workspace/myproject'
    )
    print(result.stdout)

    sandbox.kill()
    ```

    **Expected Output:**

    ```
    /workspace/myproject
    total 8
    drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
    drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
    -rw-r--r-- 1 root root    0 Jan 27 10:30 file.txt
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Create directory
    await sandbox.files.mkdir('/workspace/myproject');

    // Run command in specific directory
    const result = await sandbox.commands.run('pwd', {
      workingDir: '/workspace/myproject'
    });
    console.log(result.stdout);  // "/workspace/myproject"

    // Run multiple commands in same directory
    const multiResult = await sandbox.commands.run('touch file.txt && ls -la', {
      workingDir: '/workspace/myproject'
    });
    console.log(multiResult.stdout);

    await sandbox.kill();
    ```

    **Expected Output:**

    ```
    /workspace/myproject
    total 8
    drwxr-xr-x 2 root root 4096 Jan 27 10:30 .
    drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
    -rw-r--r-- 1 root root    0 Jan 27 10:30 file.txt
    ```
  </Tab>
</Tabs>

## Timeout Configuration

Set timeout for long-running commands:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Run command with custom timeout (5 minutes)
    result = sandbox.commands.run(
        'npm install',
        timeout=300
    )
    print(f"Installation completed: {result.success}")

    # For very long operations, use background execution instead
    sandbox.kill()
    ```

    **Expected Output:**

    ```
    Installation completed: True
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Run command with custom timeout (5 minutes)
    const result = await sandbox.commands.run('npm install', {
      timeout: 300
    });
    console.log(`Installation completed: ${result.success}`);

    // For very long operations, use background execution instead
    await sandbox.kill();
    ```

    **Expected Output:**

    ```
    Installation completed: true
    ```
  </Tab>
</Tabs>

<Warning>
  Default timeout is 30 seconds. Maximum timeout is typically 300 seconds (5 minutes) for synchronous execution. For longer-running commands, use [Background Commands](/core-concepts/commands/background) instead.
</Warning>

## Error Handling

Handle command execution errors:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox
    from hopx_ai.errors import CommandExecutionError, TimeoutError

    sandbox = Sandbox.create(template="code-interpreter")

    try:
        result = sandbox.commands.run('nonexistent-command')
        
        if not result.success:
            print(f"Command failed with exit code: {result.exit_code}")
            print(f"Error output: {result.stderr}")
        else:
            print(f"Output: {result.stdout}")
            
    except TimeoutError:
        print("Command timed out")
    except CommandExecutionError as e:
        print(f"Command execution error: {e}")

    sandbox.kill()
    ```

    **Expected Output:**

    ```
    Command failed with exit code: 127
    Error output: /bin/sh: nonexistent-command: command not found
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';
    import { CommandExecutionError, TimeoutError } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    try {
      const result = await sandbox.commands.run('nonexistent-command');
      
      if (!result.success) {
        console.error(`Command failed with exit code: ${result.exitCode}`);
        console.error(`Error output: ${result.stderr}`);
      } else {
        console.log(`Output: ${result.stdout}`);
      }
    } catch (error) {
      if (error instanceof TimeoutError) {
        console.error('Command timed out');
      } else if (error instanceof CommandExecutionError) {
        console.error(`Command execution error: ${error.message}`);
      }
    }

    await sandbox.kill();
    ```

    **Expected Output:**

    ```
    Command failed with exit code: 127
    Error output: /bin/sh: nonexistent-command: command not found
    ```
  </Tab>
</Tabs>

## Chaining Commands

Chain multiple commands together:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Chain commands with &&
    result = sandbox.commands.run('cd /workspace && mkdir test && ls -la')
    print(result.stdout)

    # Chain with pipes
    result = sandbox.commands.run('ls -la /workspace | grep .txt')
    print(result.stdout)

    # Multiple commands with semicolon
    result = sandbox.commands.run('echo "Step 1"; echo "Step 2"; echo "Step 3"')
    print(result.stdout)

    sandbox.kill()
    ```

    **Expected Output:**

    ```
    total 12
    drwxr-xr-x 3 root root 4096 Jan 27 10:30 .
    drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
    drwxr-xr-x 2 root root 4096 Jan 27 10:30 test
    Step 1
    Step 2
    Step 3
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Chain commands with &&
    const result = await sandbox.commands.run('cd /workspace && mkdir test && ls -la');
    console.log(result.stdout);

    // Chain with pipes
    const pipeResult = await sandbox.commands.run('ls -la /workspace | grep .txt');
    console.log(pipeResult.stdout);

    // Multiple commands with semicolon
    const multiResult = await sandbox.commands.run('echo "Step 1"; echo "Step 2"; echo "Step 3"');
    console.log(multiResult.stdout);

    await sandbox.kill();
    ```

    **Expected Output:**

    ```
    total 12
    drwxr-xr-x 3 root root 4096 Jan 27 10:30 .
    drwxr-xr-x 3 root root 4096 Jan 27 10:30 ..
    drwxr-xr-x 2 root root 4096 Jan 27 10:30 test
    Step 1
    Step 2
    Step 3
    ```
  </Tab>
</Tabs>

## Complete Example

Here's a complete example showing command execution workflow:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Setup project
    print("📦 Setting up project...")
    result = sandbox.commands.run('mkdir -p /workspace/myproject', timeout=10)
    print(f"  Create directory: {'✅' if result.success else '❌'}")

    # Install dependencies
    print("\n📥 Installing dependencies...")
    result = sandbox.commands.run(
        'pip install requests pandas',
        timeout=300,
        working_dir='/workspace/myproject'
    )
    if result.success:
        print("  ✅ Dependencies installed")
        print(f"  Output: {result.stdout[:100]}...")
    else:
        print(f"  ❌ Installation failed: {result.stderr}")

    # Create project files
    print("\n📝 Creating project files...")
    result = sandbox.commands.run(
        'echo "import requests" > main.py && echo "import pandas" >> main.py',
        working_dir='/workspace/myproject'
    )
    print(f"  Create files: {'✅' if result.success else '❌'}")

    # Verify setup
    print("\n🔍 Verifying setup...")
    result = sandbox.commands.run(
        'ls -la && python -c "import requests, pandas; print(\'All imports OK\')"',
        working_dir='/workspace/myproject'
    )
    if result.success:
        print("  ✅ Setup complete")
        print(f"  Output:\n{result.stdout}")
    else:
        print(f"  ❌ Verification failed: {result.stderr}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Setup project
    console.log('📦 Setting up project...');
    let result = await sandbox.commands.run('mkdir -p /workspace/myproject', { timeout: 10 });
    console.log(`  Create directory: ${result.success ? '✅' : '❌'}`);

    // Install dependencies
    console.log('\n📥 Installing dependencies...');
    result = await sandbox.commands.run('pip install requests pandas', {
      timeout: 300,
      workingDir: '/workspace/myproject'
    });
    if (result.success) {
      console.log('  ✅ Dependencies installed');
      console.log(`  Output: ${result.stdout.substring(0, 100)}...`);
    } else {
      console.error(`  ❌ Installation failed: ${result.stderr}`);
    }

    // Create project files
    console.log('\n📝 Creating project files...');
    result = await sandbox.commands.run(
      'echo "import requests" > main.py && echo "import pandas" >> main.py',
      { workingDir: '/workspace/myproject' }
    );
    console.log(`  Create files: ${result.success ? '✅' : '❌'}`);

    // Verify setup
    console.log('\n🔍 Verifying setup...');
    result = await sandbox.commands.run(
      'ls -la && python -c "import requests, pandas; print(\'All imports OK\')"',
      { workingDir: '/workspace/myproject' }
    );
    if (result.success) {
      console.log('  ✅ Setup complete');
      console.log(`  Output:\n${result.stdout}`);
    } else {
      console.error(`  ❌ Verification failed: ${result.stderr}`);
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Best Practices

<Steps>
  <Step title="1. Use Appropriate Timeouts">
    Set timeouts based on expected execution time. Default 30 seconds is good for quick commands, but increase for package installations or long operations.
  </Step>

  <Step title="2. Handle Errors Gracefully">
    Always check `result.success` and handle `stderr` appropriately. Use try/catch for exception handling.
  </Step>

  <Step title="3. Use Environment Variables">
    Pass environment variables via `env` parameter rather than hardcoding values in commands.
  </Step>

  <Step title="4. Set Working Directory">
    Use `working_dir` to run commands in the correct directory context.
  </Step>

  <Step title="5. Use Background for Long Tasks">
    For commands that run longer than 5 minutes, use [Background Commands](/core-concepts/commands/background) instead.
  </Step>
</Steps>

## Related

* **[Background Commands](/core-concepts/commands/background)** - Run commands in background
* **[Code Execution](/core-concepts/code-execution/synchronous)** - Execute code directly
* **SDK**: [sandbox.commands.run()](/sdk/python/commands#run) - Python SDK method
* **API**: [POST /commands/run](/api/vm-agent/run-command) - VM Agent API endpoint

## Next Steps

* Learn about [Background Commands](/core-concepts/commands/background) for non-blocking execution
* Explore [Code Execution](/core-concepts/code-execution/synchronous) for running code instead of shell commands
* Review [Filesystem Operations](/core-concepts/filesystem/reading) for file management

## Related

* [CLI Commands](/cli/commands/cmd) - Shell commands from CLI
