Home > Net >  pass variable from node to bash exec
pass variable from node to bash exec

Time:02-01

I am using this pattern to execute bash scripts:

const exec = util.promisify(require('child_process').exec);

async function myBash() {
    try {
        const { stdout, stderr } = await exec("echo hi");

        console.log(stdout);

    } catch (err){
       console.error(err);
    };
  };

How can I pass the variable greeting to the exec command - non working:

const exec = util.promisify(require('child_process').exec);
const greeting = "hello";

async function myBash(greeting) {
    try {
        const { stdout, stderr } = await exec("echo", greeting);

        console.log(stdout);

    } catch (err){
       console.error(err);
    };
  };

CodePudding user response:

const exec = require('child_process').exec;
const greeting = "hello";

async function myBash(greeting) {
  try {
    const {
      stdout,
      stderr
    } = await exec(`echo ${greeting}`);
    console.log(stdout);
  } catch (err) {
    console.error(err);
  };
};
myBash(greeting);

CodePudding user response:

exec will execute a command line (a string) by feeding it to a shell. You have two options:

  • Not great in this use-case: use exec with a string that incorporates arguments:

    exec(`echo '${greeting}'`);
    

    or equivalently

    exec("echo '"   greeting   "'");
    

    Note that this breaks down if the argument contains single quotes, so they need to be sanitised or properly escaped if you do not trust the arguments.

  • Much better in this case: use a function that is designed to pass arguments directly to an executable - execFile:

    execFile("echo", [greeting]);
    

    Note that this does not invoke shell; here it actually executes /bin/echo, not the bash builtin echo. It also does not parse any arguments, so wildcards, variables etc will not be substituted.

  •  Tags:  
  • Related