下面我有一个带换行符的字符串,这个字符串是一个bash文件的内容。我想知道是否有办法在不创建bash文件的情况下运行此内容。我想做类似下面的事情,我只是将内容传递给sh
命令。但是这会引发下面的错误。
let string = "\necho \'hello-world\'\n"
execAsync(`${string} | sh`)
我知道我可以使用等于当前工作目录/删除文件的路径创建临时文件/ exec。但是,如果有办法在不创建文件的情况下运行脚本,我宁愿不去解决问题。
错误:
{ Error: Command failed:
echo 'hello-world'
| sh
/bin/sh: -c: line 2: syntax error near unexpected token `|'
/bin/sh: -c: line 2: ` | sh'
at ChildProcess.exithandler (child_process.js:207:12)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:852:16)
at Socket.<anonymous> (internal/child_process.js:323:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:492:12)
cause:
{ Error: Command failed:
echo 'hello-world'
| sh
/bin/sh: -c: line 2: syntax error near unexpected token `|'
/bin/sh: -c: line 2: ` | sh'
at ChildProcess.exithandler (child_process.js:207:12)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:852:16)
at Socket.<anonymous> (internal/child_process.js:323:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:492:12)
killed: false,
code: 2,
signal: null,
cmd: '\necho \'hello-world\'\n | sh' },
isOperational: true,
killed: false,
code: 2,
signal: null,
cmd: '\necho \'hello-world\'\n | sh' }
答案 0 :(得分:0)
通过-c
选项将脚本内容传递给shell。它受到大多数炮弹的支持。
示例:
var execAsync = require('exec-async');
let script = "echo \'hello\' $(whoami)\nls -l\necho 'bye'"
execAsync('sh', ['-c', script]).then(console.log).catch(console.log);