Reading Time: < 1 minute

When you write a Node script to run generic shell commands it is worth knowing how to run multiple shell commands. child_process.exec(): spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.

Please find the sample code below:

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

let commandOne = "ls -l"; // display all files in current directory with  (-l) long format
let commandTwo = "whoami"; // print the current user
let commandThree = "pwd"; //print the name of current directory

exec(`${commandOne} && ${commandTwo} && ${commandThree}`, (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`Output: ${stdout}`);
});

Output

Output Of Above Program

This is a small article but it might save your time at some point 🙂