Nodejs 寫 Bash 腳本終極方案!
前言
最近在學(xué)習(xí)bash腳本語法,但是如果對bash語法不是熟手的話,感覺非常容易出錯,比如說:顯示未定義的變量shell中變量沒有定義,仍然是可以使用的,但是它的結(jié)果可能不是你所預(yù)期的。舉個例子:
- #!/bin/bash
- # 這里是判斷變量var是否等于字符串a(chǎn)bc,但是var這個變量并沒有聲明
- if [ "$var" = "abc" ]
- then
- # 如果if判斷里是true就在控制臺打印 “ not abc”
- echo " not abc"
- else
- # 如果if判斷里是false就在控制臺打印 “ abc”
- echo " abc "
- fi
- 復(fù)制代碼
結(jié)果是打印了abc,但問題是,這個腳本應(yīng)該報錯啊,變量并沒有賦值算是錯誤吧。
為了彌補這些錯誤,我們學(xué)會在腳本開頭加入:set \-u 這句命令的意思是腳本在頭部加上它,遇到不存在的變量就會報錯,并停止執(zhí)行。
再次運行就會提示:test.sh: 3: test.sh: num: parameter not set
再想象一下,你本來想刪除:rm \-rf $dir/*然后dir是空的時候,變成了什么?rm \-rf是刪除命令,$dir是空的話,相當于執(zhí)行 rm \-rf /*,這是刪除所有文件和文件夾。。。然后,你的系統(tǒng)就沒了,這就是傳說中的刪庫跑路嗎~~~~
如果是node或者瀏覽器環(huán)境,我們直接var === 'abc' 肯定是會報錯的,也就是說很多javascript編程經(jīng)驗無法復(fù)用到bash來,如果能復(fù)用的話,該多好啊。
后來就開始探索,如果用node腳本代替bash該多好啊,經(jīng)過一天折騰逐漸發(fā)現(xiàn)一個神器,Google旗下的zx庫,先別著急,我先不介紹這個庫,我們先看看目前主流用node如何編寫bash腳本,就知道為啥它是神器了。
node執(zhí)行bash腳本: 勉強解決方案:child_process API
例如 child_process的API里面exec命令
- const { exec } = require("child_process");
- exec("ls -la", (error, stdout, stderr) => {
- if (error) {
- console.log(`error: ${error.message}`);
- return;
- }
- if (stderr) {
- console.log(`stderr: ${stderr}`);
- return;
- }
- console.log(`stdout: ${stdout}`);
- });
- 復(fù)制代碼
這里需要注意的是,首先exec是異步的,但是我們bash腳本命令很多都是同步的。
而且注意:error對象不同于stderr. error當child_process模塊無法執(zhí)行命令時,該對象不為空。例如,查找一個文件找不到該文件,則error對象不為空。但是,如果命令成功運行并將消息寫入標準錯誤流,則該stderr對象不會為空。
當然我們可以使用同步的exec命令,execSync
- // 引入 exec 命令 from child_process 模塊
- const { execSync } = require("child_process");
- // 同步創(chuàng)建了一個hello的文件夾
- execSync("mkdir hello");
- 復(fù)制代碼
再簡單介紹一下child_process的其它能夠執(zhí)行bash命令的api
- spawn:啟動一個子進程來執(zhí)行命令
- exec:啟動一個子進程來執(zhí)行命令,與spawn不同的是,它有一個回調(diào)函數(shù)能知道子進程的情況
- execFile:啟動一子進程來執(zhí)行可執(zhí)行文件
- fork:與spawn類似,不同點是它需要指定子進程需要需執(zhí)行的javascript文件
exec跟ececFile不同的是,exec適合執(zhí)行命令,eexecFile適合執(zhí)行文件。
node執(zhí)行bash腳本: 進階方案 shelljs
- const shell = require('shelljs');
- # 刪除文件命令
- shell.rm('-rf', 'out/Release');
- // 拷貝文件命令
- shell.cp('-R', 'stuff/', 'out/Release');
- # 切換到lib目錄,并且列出目錄下到.js結(jié)尾到文件,并替換文件內(nèi)容(sed -i 是替換文字命令)
- 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('..');
- # 除非另有說明,否則同步執(zhí)行給定的命令。 在同步模式下,這將返回一個 ShellString
- #(與 ShellJS v0.6.x 兼容,它返回一個形式為 { code:..., stdout:..., stderr:... } 的對象)。
- # 否則,這將返回子進程對象,并且回調(diào)接收參數(shù)(代碼、標準輸出、標準錯誤)。
- if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
- shell.echo('Error: Git commit failed');
- shell.exit(1);
- }
- 復(fù)制代碼
從上面代碼上看來,shelljs真的已經(jīng)算是非常棒的nodejs寫bash腳本的方案了,如果你們那邊的node環(huán)境不能隨便升級,我覺得shelljs確實夠用了。
接著我們看看今天的主角zx,start已經(jīng)17.4k了。
zx庫
官方網(wǎng)址:www.npmjs.com/package/zx[1]
我們先看看怎么用
- #!/usr/bin/env zx
- await $`cat package.json | grep name`
- let branch = await $`git branch --show-current`
- await $`dep deploy --branch=${branch}`
- await Promise.all([
- $`sleep 1; echo 1`,
- $`sleep 2; echo 2`,
- $`sleep 3; echo 3`,
- ])
- let name = 'foo bar'
- await $`mkdir /tmp/${name}
- 復(fù)制代碼
各位看官覺得咋樣,是不是就是在寫linux命令而已,bash語法可以忽略很多,直接上js就行,而且它的優(yōu)點還不止這些,有一些特點挺有意思的:
1、支持ts,自動編譯.ts為.mjs文件,.mjs文件是node高版本自帶的支持es6 module的文件結(jié)尾,也就是這個文件直接import模塊就行,不用其它工具轉(zhuǎn)義
2、自帶支持管道操作pipe方法
3、自帶fetch庫,可以進行網(wǎng)絡(luò)請求,自帶chalk庫,可以打印有顏色的字體,自帶錯誤處理nothrow方法,如果bash命令出錯,可以包裹在這個方法里忽略錯誤
完整中文文檔(在下翻譯水平一般,請見諒)
- #!/usr/bin/env zx
- await $`cat package.json | grep name`
- let branch = await $`git branch --show-current`
- await $`dep deploy --branch=${branch}`
- await Promise.all([
- $`sleep 1; echo 1`,
- $`sleep 2; echo 2`,
- $`sleep 3; echo 3`,
- ])
- let name = 'foo bar'
- await $`mkdir /tmp/${name}
- 復(fù)制代碼
Bash 很棒,但是在編寫腳本時,人們通常會選擇更方便的編程語言。JavaScript 是一個完美的選擇,但標準的 Node.js 庫在使用之前需要額外的做一些事情。zx 基于 child_process ,轉(zhuǎn)義參數(shù)并提供合理的默認值。
安裝
- npm i -g zx
- 復(fù)制代碼
需要的環(huán)境
- Node.js >= 14.8.0
- 復(fù)制代碼
將腳本寫入擴展名為 .mjs 的文件中,以便能夠在頂層使用await。
將以下 shebang添加到 zx 腳本的開頭:
- #!/usr/bin/env zx
- 現(xiàn)在您將能夠像這樣運行您的腳本:
- chmod +x ./script.mjs
- ./script.mjs
- 復(fù)制代碼
或者通過 zx可執(zhí)行文件:
- zx ./script.mjs
- 復(fù)制代碼
所有函數(shù)($、cd、fetch 等)都可以直接使用,無需任何導(dǎo)入。
$`command`
使用 child_process 包中的 spawn 函數(shù)執(zhí)行給定的字符串, 并返回 ProcessPromise.
- let count = parseInt(await $`ls -1 | wc -l`)
- console.log(`Files count: ${count}`)
- 復(fù)制代碼
例如,要并行上傳文件:
如果執(zhí)行的程序返回非零退出代碼,ProcessOutput 將被拋出
- try {
- await $`exit 1`
- } catch (p) {
- console.log(`Exit code: ${p.exitCode}`)
- console.log(`Error: ${p.stderr}`)
- }
- 復(fù)制代碼
ProcessPromise,以下是promise typescript的接口定義
- class ProcessPromise<T> extends Promise<T> {
- readonly stdin: Writable
- readonly stdout: Readable
- readonly stderr: Readable
- readonly exitCode: Promise<number>
- pipe(dest): ProcessPromise<T>
- }
- 復(fù)制代碼
pipe() 方法可用于重定向標準輸出:
- await $`cat file.txt`.pipe(process.stdout)
- 復(fù)制代碼
閱讀更多的關(guān)于管道的信息 github.com/google/zx/b…[2]
ProcessOutput的typescript接口定義
- class ProcessOutput {
- readonly stdout: string
- readonly stderr: string
- readonly exitCode: number
- toString(): string
- }
- 復(fù)制代碼
函數(shù):
cd()
更改當前工作目錄
- cd('/tmp')
- await $`pwd` // outputs /tmp
- 復(fù)制代碼
fetch()
node-fetch 包。
- let resp = await fetch('http://wttr.in')
- if (resp.ok) {
- console.log(await resp.text())
- }
- 復(fù)制代碼
question()
readline包
- let bear = await question('What kind of bear is best? ')
- let token = await question('Choose env variable: ', {
- choices: Object.keys(process.env)
- })
- 復(fù)制代碼
在第二個參數(shù)中,可以指定選項卡自動完成的選項數(shù)組
以下是接口定義
- function question(query?: string, options?: QuestionOptions): Promise<string>
- type QuestionOptions = { choices: string[] }
- 復(fù)制代碼
sleep()
基于setTimeout 函數(shù)
- await sleep(1000)
- 復(fù)制代碼
nothrow()
將 $ 的行為更改, 如果退出碼不是0,不跑出異常.
ts接口定義
- function nothrow<P>(p: P): P
- 復(fù)制代碼
- await nothrow($`grep something from-file`)
- // 在管道內(nèi):
- await $`find ./examples -type f -print0`
- .pipe(nothrow($`xargs -0 grep something`))
- .pipe($`wc -l`)
- 復(fù)制代碼
以下的包,無需導(dǎo)入,直接使用
chalk
- console.log(chalk.blue('Hello world!'))
- 復(fù)制代碼
fs
類似于如下的使用方式
- import {promises as fs} from 'fs'
- let content = await fs.readFile('./package.json')
- 復(fù)制代碼
os
- await $`cd ${os.homedir()} && mkdir example`
- 復(fù)制代碼
配置:
$.shell
指定要用的bash.
- $.shell = '/usr/bin/bash'
- 復(fù)制代碼
$.quote
指定用于在命令替換期間轉(zhuǎn)義特殊字符的函數(shù)
默認用的是 shq 包.
注意:
__filename & __dirname這兩個變量是在commonjs中的。我們用的是.mjs結(jié)尾的es6 模塊。
在ESM模塊中,Node.js 不提供__filename和 __dirname 全局變量。由于此類全局變量在腳本中非常方便,因此 zx 提供了這些以在 .mjs 文件中使用(當使用 zx 可執(zhí)行文件時)
require也是commonjs中的導(dǎo)入模塊方法, 在 ESM 模塊中,沒有定義 require() 函數(shù)。zx提供了 require() 函數(shù),因此它可以與 .mjs 文件中的導(dǎo)入一起使用(當使用 zx 可執(zhí)行文件時)
傳遞環(huán)境變量
- process.env.FOO = 'bar'
- await $`echo $FOO`
- 復(fù)制代碼
傳遞數(shù)組
如果值數(shù)組作為參數(shù)傳遞給 $,數(shù)組的項目將被單獨轉(zhuǎn)義并通過空格連接 Example:
- let files = [1,2,3]
- await $`tar cz ${files}`
- 復(fù)制代碼
可以通過顯式導(dǎo)入來使用 $ 和其他函數(shù)
- #!/usr/bin/env node
- import {$} from 'zx'
- await $`date`
- 復(fù)制代碼
zx 可以將 .ts 腳本編譯為 .mjs 并執(zhí)行它們
- zx examples/typescript.ts
- 復(fù)制代碼