Skip to main content

Overview

Execute shell commands inside sandboxes using the exec() method. Commands run via /bin/sh -c, supporting pipes, variables, and shell features.

Prerequisites

Before executing commands, ensure you have:
  • Installed the Sandbox SDK (see Quickstart)
  • Created a sandbox instance
  • Basic familiarity with shell commands and async/await in JavaScript/TypeScript

Basic execution

Shell features

Commands support full shell syntax:

Options

Timeout

Set a maximum execution time (max 60 seconds):
Max per-command timeout is 60 seconds. For long-running servers, use background: true and redirect output to a log file (for example, >/tmp/server.log 2>&1).

Environment variables

Pass environment variables to individual commands using the env option:
Environment variables are merged with the sandbox’s existing environment, with your custom values taking precedence:
Environment variables are only set for the specific command execution. To persist environment variables across multiple commands, either:
  • Pass the same env object to each exec() call
  • Use shell export syntax: export VAR=value && command
  • Write them to a file and source it: source /tmp/env.sh && command

Working directory

Set a persistent working directory for commands:
Working directory persists across commands and affects exec() and file operations.

Standard input

Pass data to stdin:

Background processes

Run long-lived processes without blocking:

Real-time output streaming

Stream command output with callbacks:
Callbacks receive output line-by-line as commands execute.

Managing background processes

Check if a process is running:
Read logs from background processes:
Stop a background process:

Error handling

Common patterns

Install dependencies and run

Start server and wait for readiness

Capture output to file

Capture stderr for debugging

To capture error messages when commands fail silently, redirect stderr:

Conditional execution

Using environment variables with background processes

Combine env with background for configurable long-running services:

Best practices

  • Set timeouts: Always specify timeoutMs for potentially long operations
  • Use env option: Prefer the env option over inline export commands for cleaner, more maintainable code
  • Redirect output: For background processes, redirect to log files (>/tmp/log 2>&1)
  • Check success: Always check result.success before assuming command worked
  • Use background for servers: Don’t block on long-running processes
  • Clean up processes: Kill background processes before terminating sandbox
  • Escape carefully: Be mindful of shell escaping when passing user input
  • Secure secrets: Use the env option to pass sensitive data instead of embedding it in command strings

Limitations

  • Max timeout per command: 60 seconds
  • Background processes continue until sandbox stops or you kill them
  • No interactive TTY support
  • Commands run as root inside the container