Skip to content

Commit c9fe781

Browse files
Add env and cwd examples to execute-commands guide
Expand the execute commands guide with detailed examples of using per-command environment variables and working directories. Updates the troubleshooting section to recommend the cwd option. 🤖 Synced from cloudflare/sandbox-sdk PR #204
1 parent d35bfdf commit c9fe781

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

src/content/docs/sandbox/guides/execute-commands.mdx

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,38 @@ try {
9797
```
9898
</TypeScriptExample>
9999

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+
100132
## Execute shell commands
101133

102134
The sandbox supports shell features like pipes, redirects, and chaining:
@@ -158,14 +190,19 @@ if (!check.success) {
158190

159191
### Working directory issues
160192

161-
Use absolute paths or change directory:
193+
Use the `cwd` option for cleaner command execution:
162194

163195
<TypeScriptExample>
164196
```
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
166203
await sandbox.exec('python /workspace/my-app/script.py');
167204
168-
// Or change directory
205+
// Also works - change directory in command
169206
await sandbox.exec('cd /workspace/my-app && python script.py');
170207
```
171208
</TypeScriptExample>

0 commit comments

Comments
 (0)