Cheat Sheet速查表
跳转到主要内容

Shell.js 速查表

本文根据 Devhints / Shell.js 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2017-10-27。

ShellJS 是 Unix shell 命令在 Node.js API 的 top 上的可移植(Windows/Linux/OS X)实现。

示例

var shell = require('shelljs')
if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git')
  shell.exit(1)
}
// Copy files to release dir
shell.rm('-rf', 'out/Release')
shell.cp('-R', 'stuff/', 'out/Release')
// Replace macros in each .js file
shell.cd('lib')
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file)
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file)
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file)
})
shell.cd('..')
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed')
  shell.exit(1)
}

摘自 自述文件 (Readme).

引入 (Require)

const sh = require('shelljs')

路径

sh.cd('dir')
sh.mkdir('dir')
sh.mkdir('-p', 'dir')

文件操作

sh.cp('src', 'dest')
sh.cp('-rf', 'src', 'dest')
sh.rm('file')
sh.rm('-rf', 'file')
sh.mv('src', 'dest')
sh.mv(['src1','src2'], 'dest')
sh.chmod('644', 'file')
sh.chmod(755, 'file')
sh.chmod('u+x', 'file')

测试

sh.test('-b', 'path')  // block device
sh.test('-d', 'path')  // dir
sh.test('-e', 'path')  // exists
sh.test('-f', 'path')  // file
sh.test('-L', 'path')  // symlink

Cat 与输出

src = sh.cat('file*.txt')
'hello'.to('output.txt')
'hello'.toEnd('append.txt')
sh.cat('input.txt').to('output.txt')

工具 (Utils)

sh.which('x')
sh.pwd()
sh.echo('hi')
sh.exec('node --version').code
sh.exec('node --version').output
sh.exec('node --version', { silent: true }).output
sh.exec('node --version', (code, output) => {
  sh.echo(`exit code ${code}`)
})
sh.tempdir()
sh.error()  // null if no error

另请参阅