0

Shelljs exec command doesnot take variables. I tried all possible combinations like using double quotes, single quotes, assigning $ in front of the variable etc. below is the script:

#!/usr/bin/env node
require('shelljs');
for(let i = 0; i < data.length; i++)
{
  let dev = data[i];
  let platform_version = exec('adb -s $dev', {silent:false}).stdout;
}

error : dev not found or adds all the help commands of adb and prints out.

can anyone please help ? Thanks

note: adb is an android tool. you can use any simple commandline like echo etc

Indra4ev3r
  • 31
  • 5
  • Can you try something like this - exec('adb -s ' + dev, {silent:false}).stdout; – Rishikesh Dhokare Jan 18 '18 at 04:23
  • This works only if the variable is placed at the end. Not sure how to get it working when a variable is in between the shell command. I posted the answer using template literals – Indra4ev3r Jan 19 '18 at 21:52

2 Answers2

2

You cannot do string interpolation in JavaScript like 'adb -s $dev'. The $dev variable will not be replaced by its value. You can use the + operator instead to form the string. See the code below.

let platform_version = exec('adb -s ' + dev, {silent:false}).stdout;

Note: In ECMAScript 6, you can use template literals to get similar result since they allow string interpolation. Template literals are written within ` (backticks). Which means the code `adb -s ${dev}` should also give the desired result.

Vivek
  • 2,665
  • 1
  • 18
  • 20
1

Using Template Literals we can solve the issue. But there is a small change in the variables.

let platform_version = exec(`adb -s ${dev}`, {silent:false}).stdout;

Need to use wrap the variable in curly braces to get the desired result.

Al.G.
  • 4,327
  • 6
  • 31
  • 56
Indra4ev3r
  • 31
  • 5