---
title: Package Scripts
summary: Automate repeat work with scripts in box.json, run them by name, and hook into CommandBox lifecycle events.
icon: phosphor-duotone:terminal-window
tags: [course]
---

In this lesson you will add scripts to your `box.json`, run them with `run-script`, and attach commands to lifecycle events like installs and server starts.

## Ad-hoc scripts

A `scripts` struct in `box.json` holds named commands. Each value is any command you could type in the CommandBox shell.

```json title="box.json"
{
  "name": "My Package",
  "slug": "my-package",
  "version": "1.0.0",
  "scripts": {
    "generateAPIDocs": "docbox generate",
    "build": "testbox run && run-script generateAPIDocs"
  }
}
```

Run them by name:

```bash
box run-script generateAPIDocs
box run-script build
```

A command that errors stops the chain, just like `&&` in a shell.

## Several commands as a list

For readability, a script can be an array. It behaves the same as joining the commands with `&&`.

```json title="box.json"
{
  "scripts": {
    "build": [
      "testbox run",
      "run-script generateAPIDocs",
      "bump --patch"
    ]
  }
}
```

## Passing parameters

Extra arguments to `run-script` become environment variables inside the script.

```bash
box run-script greet Luis
```

```json title="box.json"
{
  "scripts": {
    "greet": "echo Hello ${1}"
  }
}
```

Named form: every argument must be named, including the script name.

```bash
box run-script scriptName=greet name1=Luis
```

## pre and post scripts

Before any script runs, CommandBox looks for a script with the same name prefixed with `pre`. After it, it looks for one prefixed with `post`. So `build` runs as `preBuild`, `build`, `postBuild`.

## Lifecycle hooks

Scripts named after a CommandBox interception point run automatically when that event fires. The ones you will use most:

| Script name | Fires |
|-------------|-------|
| `preInstall` | before a package is installed |
| `postInstall` | after an install completes |
| `preServerStart` | before a server starts |
| `onServerInstall` | when a server starts and its engine is being installed |

```json title="box.json"
{
  "scripts": {
    "postInstall": "echo Install finished",
    "onServerStart": "touch ${interceptData.serverInfo.serverHomeDirectory}/hi.txt"
  }
}
```

!!! tip "Intercept data"
    Hooks can read event data as environment variables prefixed with `interceptData.`. Use `env show` inside a script to dump what is available.

Server related scripts can also live in a project's `server.json`.

## Recap

- Put named commands under `scripts` in `box.json` and run them with `box run-script <name>`.
- Scripts can be arrays, take parameters as `${1}` or `${name}`, and get `pre` and `post` variants for free.
- Name a script after an interception point such as `postInstall` or `preServerStart` and it runs on that event.
