OSDN Git Service

Regular updates
[twpd/master.git] / shelljs.md
1 ---
2 title: Shell.js
3 category: JavaScript libraries
4 layout: 2017/sheet
5 updated: 2017-10-27
6 weight: -1
7 intro: |
8   [ShellJS](https://github.com/shelljs/shelljs) is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. 
9 ---
10
11 ### Example
12
13 ```js
14 var shell = require('shelljs')
15 ```
16
17 ```js
18 if (!shell.which('git')) {
19   shell.echo('Sorry, this script requires git')
20   shell.exit(1)
21 }
22 ```
23
24 ```js
25 // Copy files to release dir
26 shell.rm('-rf', 'out/Release')
27 shell.cp('-R', 'stuff/', 'out/Release')
28 ```
29
30 ```js
31 // Replace macros in each .js file
32 shell.cd('lib')
33 shell.ls('*.js').forEach(function (file) {
34   shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file)
35   shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file)
36   shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file)
37 })
38 shell.cd('..')
39 ```
40
41 ```js
42 // Run external tool synchronously
43 if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
44   shell.echo('Error: Git commit failed')
45   shell.exit(1)
46 }
47 ```
48
49 Taken from the [Readme](https://github.com/shelljs/shelljs).
50
51 ### Require
52
53 ```js
54 const sh = require('shelljs')
55 ```
56
57 ### Paths
58
59 ```js
60 sh.cd('dir')
61 ```
62
63 ```js
64 sh.mkdir('dir')
65 sh.mkdir('-p', 'dir')
66 ```
67
68 ### File manipulation
69
70 ```js
71 sh.cp('src', 'dest')
72 sh.cp('-rf', 'src', 'dest')
73 ```
74
75 ```js
76 sh.rm('file')
77 sh.rm('-rf', 'file')
78 ```
79
80 ```js
81 sh.mv('src', 'dest')
82 sh.mv(['src1','src2'], 'dest')
83 ```
84
85 ```js
86 sh.chmod('644', 'file')
87 sh.chmod(755, 'file')
88 sh.chmod('u+x', 'file')
89 ```
90
91 ### Tests
92
93 ```js
94 sh.test('-b', 'path')  // block device
95 sh.test('-d', 'path')  // dir
96 sh.test('-e', 'path')  // exists
97 sh.test('-f', 'path')  // file
98 sh.test('-L', 'path')  // symlink
99 ```
100
101 ### Cat and output
102
103 ```js
104 src = sh.cat('file*.txt')
105 ```
106
107 ```js
108 'hello'.to('output.txt')
109 'hello'.toEnd('append.txt')
110 ```
111
112 ```js
113 sh.cat('input.txt').to('output.txt')
114 ```
115
116 ### Utils
117
118 ```js
119 sh.which('x')
120 sh.pwd()
121 ```
122
123 ```js
124 sh.echo('hi')
125 ```
126
127 ```js
128 sh.exec('node --version').code
129 sh.exec('node --version').output
130 sh.exec('node --version', { silent: true }).output
131 ```
132
133 ```js
134 sh.exec('node --version', (code, output) => {
135   sh.echo(`exit code ${code}`)
136 })
137 ```
138
139 ```js
140 sh.tempdir()
141 ```
142
143 ```js
144 sh.error()  // null if no error
145 ```
146
147 ## Also see
148
149 * <https://github.com/shelljs/shelljs>