Post

Bun shell for multiline commands

Bun shell is great for shorter commands, but when they become too long, then it gets a bit tricky. Thankfully, there is {raw: } feature, that can help us to handle numerous arguments and long commands.

Let’s make a helper function sh():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { $ } from "bun";

function sh(...args) {
  const raw = args.map((a) => {
    if (Array.isArray(a)) {
      return a.map(String).join(' ');
    } else if (typeof a === 'object') {
      return Object.entries(a).map(([k, v]) => `--${k}="${v}"`).join(' ');
    } else {
      return `${a}`;
    }
  }).join(' ');
  console.log(`$ ${raw}`);
  return $`${{raw}}`;
}

and then use it for our SQS example from the previous post:

1
2
3
4
5
6
7
(
  await sh(`aws sqs receive-message`, {
    'queue-url': Bun.argv[2],
    'max-number-of-messages': 10,
  }).json()
).Messages.forEach((msg) => {
  ...

Almost perfect! Maybe one day Bun can do it for us out of the box 🤞

This post is licensed under CC BY 4.0 by the author.