Skip to content

Commit

Permalink
Fix shell backticks crash (#13375)
Browse files Browse the repository at this point in the history
  • Loading branch information
zackradisic authored Aug 18, 2024
1 parent 63596c3 commit 58d02e4
Show file tree
Hide file tree
Showing 2 changed files with 248 additions and 152 deletions.
49 changes: 49 additions & 0 deletions docs/runtime/shell.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,55 @@ const result = await $`cat < ${response} | wc -w`.text();
console.log(result); // 6\n
```

## Command substitution (`$(...)`)

Command substitution allows you to substitute the output of another script into the current script:

```js
import { $ } from "bun";

// Prints out the hash of the current commit
await $`echo Hash of current commit: $(git rev-parse HEAD)`;
```

This is a textual insertion of the command's output and can be used to, for example, declare a shell variable:

```js
import { $ } from "bun";

await $`
REV=$(git rev-parse HEAD)
docker built -t myapp:$REV
echo Done building docker image "myapp:$REV"
`;
```

{% callout %}

**NOTE**: Because Bun internally uses the special [`raw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#raw_strings) property on the input template literal, using the backtick syntax for command substitution won't work:

```js
import { $ } from "bun";

await $`echo \`echo hi\``;
```

Instead of printing:

```
hi
```

The above will print out:

```
echo hi
```

We instead recommend sticking to the `$(...)` syntax.

{% /callout %}

## Environment variables

Environment variables can be set like in bash:
Expand Down
Loading

0 comments on commit 58d02e4

Please sign in to comment.