1

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);
    };
  };

2 Answers 2

2
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);
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.