<span id="text"></span>
function sh(pieces, ...args) {
  let cmd = pieces[0]; 
  let i = 0;
  while (i < args.length) {
    if(Array.isArray(args[i])) {
      cmd += args[i].join(' ');
      cmd += pieces[++i];
    } else {
      cmd += args[i] + pieces[++i];
    }
  }

  return parse_cmd(cmd);
}

function parse_cmd(str) {
  let result = [];
  let log_matches = false;

  let regex = /(([\w-/_~\.]+)|("(.*?)")|('(.*?)'))/g;
  let groups = [2, 4, 6];
  let match;

  while ((match = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (match.index === regex.lastIndex) {
      regex.lastIndex++;
    }

    // For this to work the regex groups need to be mutually exclusive 
    groups.forEach(function(group) {
      if(match[group]) {
        result.push(match[group]);
      }
    });

    // For debugging
    log_matches && match.forEach(function(m, group) {
      if(m) {
        console.log(`Match '${m}' found in group: ${group}`);
      }
    });
  }
  
  return result;
}

function array_to_object(state, value, index) {
  state[index] = value;
  return state;
}

let args = ['query', '~/bin/st4f_f'];

let result = sh`node ./src/1-main-test2.js -i 'thing "what"' --some "stuff 'now'" HellO ${args}`;

result = result.reduce(array_to_object, {});
text.innerHTML = '<pre>' + JSON.stringify(result, null, 2) + '</pre>';

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.