---
title: Run Bash Script from Node
date: 2018-09-22
tags: bash, node, scripts
source: https://brianchildress.co/blog/run-bash-script-from-node
---

# Run Bash Script from Node

I recently needed a way to execute a bash script from a Node application. The premise was simple, to create an authorization protected Node/Express endpoint that could execute a bash script that lives alongside my app. My script does tasks like moving local log files and restarting processes. Node makes this extremely easy to do.

_Problem:_ Run bash script from Node Application

_Solution:_

By leveraging the child processes in Node I can [spawn a new child process](https://nodejs.org/api/child_process.html) to execute the script. Spawning allows separate child processes to run asynchronously. Here I will show an example using a `setInterval()`, but this can easily be added to any other portion of your Node app, like a JWT protected endpoint.

_app.js_
```js

'use strict'

const child_process = require("child_process");

setInterval(() => {

  const child = child_process.spawn('bash', [__dirname + '/myscript.sh']);

  child.on('exit', () => {
    console.log('process complete');
  });

}, 3000);

```

This will simply execute `myscript.sh` every 3 seconds, console logging when the _child_process_ is complete.

To breakdown each line:

`const child = child_process.spawn('bash', [__dirname + '/myscript.sh']);`

This is creating a new constant variable call `child` and setting it to a new `child_process.spawn()`. The spawn will the execute our _myscript.sh_ as a 'bash' script.

The child_process.spawn() produces a few different events, here we are listening for the `exit` event and console.log()'ing that the process completed.
