|
97 | 97 | ``` |
98 | 98 | </TypeScriptExample> |
99 | 99 |
|
| 100 | +## Set environment variables and working directory |
| 101 | + |
| 102 | +Use the `env` and `cwd` options to customize command execution without affecting the session: |
| 103 | + |
| 104 | +<TypeScriptExample> |
| 105 | +``` |
| 106 | +// Set environment variables for a single command |
| 107 | +const result = await sandbox.exec('npm test', { |
| 108 | + env: { |
| 109 | + NODE_ENV: 'test', |
| 110 | + CI: 'true', |
| 111 | + DATABASE_URL: 'postgres://localhost/test_db' |
| 112 | + } |
| 113 | +}); |
| 114 | +
|
| 115 | +// Change working directory for a single command |
| 116 | +const build = await sandbox.exec('npm run build', { |
| 117 | + cwd: '/workspace/my-app' |
| 118 | +}); |
| 119 | +
|
| 120 | +// Combine both options |
| 121 | +const test = await sandbox.exec('pytest', { |
| 122 | + env: { PYTHONPATH: '/workspace/lib' }, |
| 123 | + cwd: '/workspace/tests' |
| 124 | +}); |
| 125 | +``` |
| 126 | +</TypeScriptExample> |
| 127 | + |
| 128 | +:::note |
| 129 | +Per-command environment variables are **merged** with session environment variables. Per-command working directory **overrides** the session working directory. These changes only affect the current command and do not persist to the session. |
| 130 | +::: |
| 131 | + |
100 | 132 | ## Execute shell commands |
101 | 133 |
|
102 | 134 | The sandbox supports shell features like pipes, redirects, and chaining: |
@@ -158,14 +190,19 @@ if (!check.success) { |
158 | 190 |
|
159 | 191 | ### Working directory issues |
160 | 192 |
|
161 | | -Use absolute paths or change directory: |
| 193 | +Use the `cwd` option for cleaner command execution: |
162 | 194 |
|
163 | 195 | <TypeScriptExample> |
164 | 196 | ``` |
165 | | -// Use absolute path |
| 197 | +// Best - use cwd option |
| 198 | +await sandbox.exec('python script.py', { |
| 199 | + cwd: '/workspace/my-app' |
| 200 | +}); |
| 201 | +
|
| 202 | +// Alternative - use absolute path |
166 | 203 | await sandbox.exec('python /workspace/my-app/script.py'); |
167 | 204 |
|
168 | | -// Or change directory |
| 205 | +// Also works - change directory in command |
169 | 206 | await sandbox.exec('cd /workspace/my-app && python script.py'); |
170 | 207 | ``` |
171 | 208 | </TypeScriptExample> |
|
0 commit comments