使用Shell.js将exec stdout与一些文本进行比较

时间:2019-04-26 17:18:12

标签: javascript node.js shell shelljs

运行sh.exec('whoami')时,我正在尝试比较标准输出,但它不起作用。

我想做的是,在运行whoami命令后,如果结果变成了特定用户,那么我想触发一个动作。

运行时,

sh.exec('whoami', (code, output) => {
  sh.echo(output == 'myusername'); // False
  console.log(output == 'myusername'); // False
});

由于我已经复制了用户名并将其放置为比较字符串,因此即使我完全确定条件output == 'myusername'的计算结果也为false。

预期结果将是条件评估为真。

1 个答案:

答案 0 :(得分:0)

正在做

 console.log(sh.exec('whoami'));

您将获得以下输出,

{ [String: 'username\n']
  stdout: 'username\n',
  stderr: '',
  code: 0,
  cat: [Function: bound ],
  exec: [Function: bound ],
  grep: [Function: bound ],
  head: [Function: bound ],
  sed: [Function: bound ],
  sort: [Function: bound ],
  tail: [Function: bound ],
  to: [Function: bound ],
  toEnd: [Function: bound ],
  uniq: [Function: bound ] 
}

问题只是换行了。 stdout的末尾带有\n