How to Run a Bash Script with Node.js

Recently, for the first time, I needed to run Bash scripts from within my Node.js app. Now that I know how, I think it could be handy for many things. Here's how to do it:

Create a Bash Script

First, let's create a simple Bash script that we'll run from our Node.js application. Create a new file called hello.sh with the following content:

#!/bin/bash
echo "Hello from Bash!"
echo "Current date: $(date)"
echo "Arguments received: $@"

Make sure to make the script executable by running the following in your bash shell:

bash hello.sh test-arg

You should see the following as an output:

Hello from Bash!
Current date: Wed 28 Aug 2024 18:29:37 IST
Arguments received: test-arg

Create a Node.js Script

Now, let's create a Node.js script to execute our Bash script. Create a new file called run_bash.js with the following content:

const { exec } = require('child_process');

// Function to execute the Bash script
function runBashScript(scriptPath, args = []) {
  return new Promise((resolve, reject) => {
    const command = `${scriptPath} ${args.join(' ')}`;
    
    exec(command, (error, stdout, stderr) => {
      if (error) {
        reject(`Error: ${error.message}`);
        return;
      }
      if (stderr) {
        reject(`stderr: ${stderr}`);
        return;
      }
      resolve(stdout);
    });
  });
}

// Usage
const scriptPath = './hello.sh';
const args = ['arg1', 'arg2', 'arg3'];

runBashScript(scriptPath, args)
  .then((output) => {
    console.log('Bash script output:');
    console.log(output);
  })
  .catch((error) => {
    console.error('Error running Bash script:', error);
  });

Run the Node.js Script

Now you can run the Node.js script, which will in turn, execute the Bash script:

node run_bash.js

You should see output similar to this:

Bash script output:
Hello from Bash!
Current date: Wed 28 Aug 2024 18:31:13 IST
Arguments received: arg1 arg2 arg3

How It Works

The magic is simply running shell commands using the child_process.exec() method from Node.js.

The runBashScript() function takes the path to the Bash script and an optional array of arguments. We construct the command string by combining the script path and arguments.

The exec() method executes the command and returns the result via a callback. We wrap this in a Promise for easier handling and to allow the use of async/await if desired.

Quick tip/warning: Always prioritize security and error handling when working with system-level scripts. Scripts can cause chaos with systems if you don't know what you're doing.

NodejsBash
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.