nodejs 写 bash 脚本终极方案!

开发 前端
最近在学习bash脚本语法,但是如果对bash语法不是熟手的话,感觉非常容易出错,比如说:显示未定义的变量shell中变量没有定义,仍然是可以使用的,但是它的结果可能不是你所预期的。

[[423829]]

 前言

最近在学习bash脚本语法,但是如果对bash语法不是熟手的话,感觉非常容易出错,比如说:显示未定义的变量shell中变量没有定义,仍然是可以使用的,但是它的结果可能不是你所预期的。举个例子: 

  1. #!/bin/bash  
  2. # 这里是判断变量var是否等于字符串abc,但是var这个变量并没有声明  
  3. if [ "$var" = "abc" ]   
  4. then  
  5.    # 如果if判断里是true就在控制台打印 “ not abc”  
  6.    echo  " not abc"   
  7. else  
  8.    # 如果if判断里是false就在控制台打印 “ abc”  
  9.    echo " abc "  
  10. fi 

结果是打印了abc,但问题是,这个脚本应该报错啊,变量并没有赋值算是错误吧。

为了弥补这些错误,我们学会在脚本开头加入:set \-u 这句命令的意思是脚本在头部加上它,遇到不存在的变量就会报错,并停止执行。

再次运行就会提示:test.sh: 3: test.sh: num: parameter not set

再想象一下,你本来想删除:rm \-rf $dir/*然后dir是空的时候,变成了什么?rm \-rf是删除命令,$dir是空的话,相当于执行 rm \-rf /*,这是删除所有文件和文件夹。。。然后,你的系统就没了,这就是传说中的删库跑路吗~~~~

如果是node或者浏览器环境,我们直接var === 'abc' 肯定是会报错的,也就是说很多javascript编程经验无法复用到bash来,如果能复用的话,该多好啊。

后来就开始探索,如果用node脚本代替bash该多好啊,经过一天折腾逐渐发现一个神器,Google旗下的zx库,先别着急,我先不介绍这个库,我们先看看目前主流用node如何编写bash脚本,就知道为啥它是神器了。

node执行bash脚本: 勉强解决方案:child_process API

例如 child_process的API里面exec命令 

  1. const { exec } = require("child_process");  
  2. exec("ls -la", (error, stdout, stderr) => {  
  3.     if (error) {  
  4.         console.log(`error: ${error.message}`);  
  5.         return;  
  6.     }  
  7.     if (stderr) {  
  8.         console.log(`stderr: ${stderr}`);  
  9.         return;  
  10.     }  
  11.     console.log(`stdout: ${stdout}`);  
  12. }); 

这里需要注意的是,首先exec是异步的,但是我们bash脚本命令很多都是同步的。

而且注意:error对象不同于stderr. error当child_process模块无法执行命令时,该对象不为空。例如,查找一个文件找不到该文件,则error对象不为空。但是,如果命令成功运行并将消息写入标准错误流,则该stderr对象不会为空。

当然我们可以使用同步的exec命令,execSync 

  1. // 引入 exec 命令 from child_process 模块  
  2. const { execSync } = require("child_process");  
  3. // 同步创建了一个hello的文件夹  
  4. execSync("mkdir hello"); 

再简单介绍一下child_process的其它能够执行bash命令的api

  •  spawn:启动一个子进程来执行命令
  •  exec:启动一个子进程来执行命令,与spawn不同的是,它有一个回调函数能知道子进程的情况
  •  execFile:启动一子进程来执行可执行文件
  •  fork:与spawn类似,不同点是它需要指定子进程需要需执行的javascript文件

exec跟ececFile不同的是,exec适合执行命令,eexecFile适合执行文件。

node执行bash脚本: 进阶方案 shelljs 

  1. const shell = require('shelljs');   
  2. # 删除文件命令  
  3. shell.rm('-rf', 'out/Release');  
  4. // 拷贝文件命令  
  5. shell.cp('-R', 'stuff/', 'out/Release');   
  6. # 切换到lib目录,并且列出目录下到.js结尾到文件,并替换文件内容(sed -i 是替换文字命令)  
  7. shell.cd('lib');  
  8. shell.ls('*.js').forEach(function (file) {  
  9.   shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);  
  10.   shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);  
  11.   shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);  
  12. });  
  13. shell.cd('..');  
  14. # 除非另有说明,否则同步执行给定的命令。 在同步模式下,这将返回一个 ShellString  
  15. #(与 ShellJS v0.6.x 兼容,它返回一个形式为 { code:..., stdout:..., stderr:... } 的对象)。 
  16. # 否则,这将返回子进程对象,并且回调接收参数(代码、标准输出、标准错误)。  
  17. if (shell.exec('git commit -am "Auto-commit"').code !== 0) {  
  18.   shell.echo('Error: Git commit failed');  
  19.   shell.exit(1);  

从上面代码上看来,shelljs真的已经算是非常棒的nodejs写bash脚本的方案了,如果你们那边的node环境不能随便升级,我觉得shelljs确实够用了。

接着我们看看今天的主角zx,start已经17.4k了。

zx库

官方网址:www.npmjs.com/package/zx

我们先看看怎么用 

  1. #!/usr/bin/env zx  
  2. await $`cat package.json | grep name`  
  3. let branch = await $`git branch --show-current`  
  4. await $`dep deploy --branch=${branch}`  
  5. await Promise.all([  
  6.   $`sleep 1; echo 1`,  
  7.   $`sleep 2; echo 2`,  
  8.   $`sleep 3; echo 3`,  
  9. ])  
  10. let name = 'foo bar'  
  11. await $`mkdir /tmp/${name} 

各位看官觉得咋样,是不是就是在写linux命令而已,bash语法可以忽略很多,直接上js就行,而且它的优点还不止这些,有一些特点挺有意思的:

1、支持ts,自动编译.ts为.mjs文件,.mjs文件是node高版本自带的支持es6 module的文件结尾,也就是这个文件直接import模块就行,不用其它工具转义

2、自带支持管道操作pipe方法

3、自带fetch库,可以进行网络请求,自带chalk库,可以打印有颜色的字体,自带错误处理nothrow方法,如果bash命令出错,可以包裹在这个方法里忽略错误

完整中文文档(在下翻译水平一般,请见谅) 

  1. #!/usr/bin/env zx  
  2. await $`cat package.json | grep name`  
  3. let branch = await $`git branch --show-current`  
  4. await $`dep deploy --branch=${branch}`  
  5. await Promise.all([  
  6.   $`sleep 1; echo 1`,  
  7.   $`sleep 2; echo 2`,  
  8.   $`sleep 3; echo 3`,  
  9. ])  
  10. let name = 'foo bar'  
  11. await $`mkdir /tmp/${name} 

Bash 很棒,但是在编写脚本时,人们通常会选择更方便的编程语言。JavaScript 是一个完美的选择,但标准的 Node.js 库在使用之前需要额外的做一些事情。zx 基于 child_process ,转义参数并提供合理的默认值。

安装

  1. npm i -g zx 

需要的环境

  1. Node.js >= 14.8.0 

将脚本写入扩展名为 .mjs 的文件中,以便能够在顶层使用await。

将以下 shebang添加到 zx 脚本的开头: 

  1. #!/usr/bin/env zx  
  2. 现在您将能够像这样运行您的脚本:  
  3. chmod +x ./script.mjs  
  4. ./script.mjs 

或者通过 zx可执行文件: 

  1. zx ./script.mjs 

所有函数($、cd、fetch 等)都可以直接使用,无需任何导入。

$command

使用 child_process 包中的 spawn 函数执行给定的字符串, 并返回 ProcessPromise. 

  1. let count = parseInt(await $`ls -1 | wc -l`)console.log(`Files count: ${count}`) 

例如,要并行上传文件:

如果执行的程序返回非零退出代码,ProcessOutput 将被抛出 

  1. try {  
  2.   await $`exit 1`  
  3. } catch (p) {  
  4.   console.log(`Exit code: ${p.exitCode}`)  
  5.   console.log(`Error: ${p.stderr}`)  

ProcessPromise,以下是promise typescript的接口定义 

  1. class ProcessPromise<T> extends Promise<T> {  
  2.   readonly stdin: Writable  
  3.   readonly stdout: Readable  
  4.   readonly stderr: Readable  
  5.   readonly exitCode: Promise<number>  
  6.   pipe(dest): ProcessPromise<T>  

pipe() 方法可用于重定向标准输出:

  1. await $`cat file.txt`.pipe(process.stdout) 

阅读更多的关于管道的信息 github.com/google/zx/b…

ProcessOutput的typescript接口定义 

  1. class ProcessOutput {  
  2.   readonly stdout: string  
  3.   readonly stderr: string  
  4.   readonly exitCode: number  
  5.   toString(): string  

函数:

cd()

更改当前工作目录 

  1. cd('/tmp')await $`pwd` // outputs /tmp 

fetch()

node-fetch 包。 

  1. let resp = await fetch('http://wttr.in')  
  2. if (resp.ok) {  
  3.   console.log(await resp.text())  

question()

readline包 

  1. let bear = await question('What kind of bear is best? ')  
  2. let token = await question('Choose env variable: ', {  
  3.   choices: Object.keys(process.env)  
  4. }) 

在第二个参数中,可以指定选项卡自动完成的选项数组

以下是接口定义 

  1. function question(query?: string, options?: QuestionOptions): Promise<string>  
  2. type QuestionOptions = { choices: string[] } 

sleep()

基于setTimeout 函数

  1. await sleep(1000) 

nothrow()

将 $ 的行为更改, 如果退出码不是0,不跑出异常.

ts接口定义 

  1. function nothrow<P>(p: P): P  
  1. await nothrow($`grep something from-file`)  
  2. // 在管道内:  
  3. await $`find ./examples -type f -print0`  
  4.   .pipe(nothrow($`xargs -0 grep something`))  
  5.   .pipe($`wc -l`) 

以下的包,无需导入,直接使用

chalk 

  1. console.log(chalk.blue('Hello world!')) 

fs

类似于如下的使用方式 

  1. import {promises as fs} from 'fs'  
  2. let content = await fs.readFile('./package.json') 

os 

  1. await $`cd ${os.homedir()} && mkdir example` 

配置:

$.shell

指定要用的bash.

  1. $.shell = '/usr/bin/bash' 

$.quote

指定用于在命令替换期间转义特殊字符的函数

默认用的是 shq 包.

注意:

__filename & __dirname这两个变量是在commonjs中的。我们用的是.mjs结尾的es6 模块。

在ESM模块中,Node.js 不提供__filename和 __dirname 全局变量。由于此类全局变量在脚本中非常方便,因此 zx 提供了这些以在 .mjs 文件中使用(当使用 zx 可执行文件时)

require也是commonjs中的导入模块方法, 在 ESM 模块中,没有定义 require() 函数。zx提供了 require() 函数,因此它可以与 .mjs 文件中的导入一起使用(当使用 zx 可执行文件时)

传递环境变量 

  1. process.env.FOO = 'bar'  
  2. await $`echo $FOO`  

传递数组

如果值数组作为参数传递给 $,数组的项目将被单独转义并通过空格连接 Example: 

  1. let files = [1,2,3]  
  2. await $`tar cz ${files}` 

可以通过显式导入来使用 $ 和其他函数 

  1. #!/usr/bin/env node  
  2. import {$} from 'zx'  
  3. await $`date` 

zx 可以将 .ts 脚本编译为 .mjs 并执行它们 

  1. zx examples/typescript.ts  

 

责任编辑:庞桂玉 来源: 前端大全
相关推荐

2021-08-30 12:45:37

nodejsbash前端

2020-09-11 16:00:40

Bash单元测试

2022-03-10 10:12:04

自动化脚本Bash

2023-08-23 12:12:45

BashLinux

2022-05-30 10:31:34

Bash脚本Linux

2021-05-19 17:25:12

Pythonexe命令

2014-08-05 11:17:28

Bash脚本测试

2022-12-01 08:10:49

Bash脚本参数

2023-08-29 08:57:03

事务脚本架构模式业务场景

2022-01-20 16:43:38

Bash 脚本ShellLinux

2022-02-28 11:02:53

函数Bash Shell语句

2020-10-13 19:04:58

Bash信号捕获Shell脚本

2021-12-30 10:26:37

Bash Shell脚本文件命令

2017-04-13 10:51:17

Bash建议

2021-03-11 21:30:43

BATSBash软件开发

2021-02-01 11:01:18

Bash脚本Linux

2022-11-30 07:47:00

Bash脚本

2022-11-25 07:53:26

bash脚本字符串

2010-06-23 15:55:36

Linux Bash

2014-04-22 09:42:12

Bash脚本教程
点赞
收藏

51CTO技术栈公众号