Learn how to execute shell commands in sandboxes with streaming output, timeouts, and environment variables.
The Sandbox SDK provides flexible command execution through the exec() method. You can run any shell command and get immediate results, or stream output in real-time for long-running operations.
Every exec() call returns an ExecResult object with complete execution details:
interface ExecResult { success: boolean; // true if exitCode === 0 exitCode: number; // Process exit code stdout: string; // Standard output content stderr: string; // Standard error content command: string; // Command that was executed duration: number; // Execution time in milliseconds timestamp: string; // ISO timestamp when command started sessionId?: string; // Session ID if provided}
Environment variables passed to exec() only apply to that specific command. They don’t persist in the session. Use setEnvVars() for persistent environment variables.
Stream output for commands that take more than a few seconds. This provides user feedback and helps debug issues.
3
Set appropriate timeouts
4
Always set timeouts for operations that might hang. This prevents resource exhaustion and provides better error messages.
5
Handle errors explicitly
6
Check result.success before using command output. Non-zero exit codes indicate failures that need handling.
7
Escape special characters
8
When constructing commands with user input, properly escape special characters or use command arrays:
9
// Bad - vulnerable to injectionawait sandbox.exec(`cat ${userFilename}`);// Good - escape shell special charactersimport { shellEscape } from '@repo/shared';await sandbox.exec(`cat ${shellEscape(userFilename)}`);