Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pass variable from node to bash exec

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading