DEV Community

loading...

Shell.Js Cheat Sheet

hoanganhlam profile image Lâm ・2 min read

Also see

Utils

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

Cat and output

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

Tests

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
Enter fullscreen mode Exit fullscreen mode

File manipulation

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

Paths

sh.cd('dir')
Enter fullscreen mode Exit fullscreen mode
sh.mkdir('dir')
sh.mkdir('-p', 'dir')
Enter fullscreen mode Exit fullscreen mode

Require

const sh = require('shelljs')
Enter fullscreen mode Exit fullscreen mode

Example

var shell = require('cs/shelljs')
Enter fullscreen mode Exit fullscreen mode
if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git')
  shell.exit(1)
}
Enter fullscreen mode Exit fullscreen mode
// Copy files to release dir
shell.rm('-rf', 'out/Release')
shell.cp('-R', 'stuff/', 'out/Release')
Enter fullscreen mode Exit fullscreen mode
// 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('..')
Enter fullscreen mode Exit fullscreen mode
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed')
  shell.exit(1)
}
Enter fullscreen mode Exit fullscreen mode

Taken from the Readme.

Discussion (0)

Forem Open with the Forem app