0

I’ve written a node script that cd’s into multiple directories in sequence and executes bash commands in order to deploy the contents of the repos to my development environment.

Native bash commands work fine, like cd, ls, but it looks like the subshell or child process (or whatever the proper term is, I don’t understand the inner workings of Bash) that’s opened by node doesn’t have anything available to my normal prompt.

E.g.

  • the custom bash toolset that’s available globally
  • nvm (is this even possible, to run a different version of node within a node subshell?)
  • gulp breaks because it doesn't have the necessary node version installed.

Is it possible to access these programs/commands from the node subshell? I’m using the child_process node module.

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

function command (command) {
    exec (command, (err, stdout, stderr) => {
        if (err) {
            error(err);
        } else {
            message(`stdout: ${stdout}`);
            message(`stderr: ${stderr}`);
        }
    });
}

Used as in:

command('nvm use 6');
command('gulp build');
command('pde deploy');
beingmrkenny
  • 192
  • 1
  • 10
  • Found the answer on https://stackoverflow.com/questions/43725871/nodejs-child-process-exec-command-failed-with-nvm-permission-denied-osx – beingmrkenny Apr 07 '20 at 15:16

1 Answers1

0

The child process is not run as bash. child_process spawns the executable using the regular sh shell. If you need the commands to run within bash, the command line you run needs to be wrapped in bash -c. For example:

command('bash -c "my command here"');

Also, each command you run is a sub-process, which does not affect the parent process, nor any subsequent sub processes. Thus, a shell built-in like cd will only change the directory for that sub-process, which immediately goes away. You will see this if you run:

command('cd /');
command('ls');

The ls command will show the current working directory, not the root directory.

If you run your command with bash -c and the $PATH and other environment variables still aren't set up the way you need them, you need to debug your shell start-up scripts. Perhaps there's a difference between interactive shells (.bash_profile) and all shells (.bashrc).

Note that fully non-interactive shells may need to explicitly have the start-up script you want to run specified.

Jon Watte
  • 6,579
  • 4
  • 53
  • 63