Forward
不知道您在使用linux系统时,是否经常需要编写脚本来处理复杂、重复的场景?比如对“独立程序”的启动、停止、暂定、状态检查,比如多台机器替换相同的文件,等等……
对于一些逻辑简单的轻量级脚本,linux环境下使用bash来完成会是大部分人的首选,bash可在无任何其它语言或第三方依赖的安装环境下,快速写出脚本程序。
小编入门bash时,是通过“《菜鸟教程》系列文章” + “项目中shell实例”,一步步掌握其编写技巧的。经历了“从渐渐可以看懂,到一点点可以自己写”的过程后,越发觉得菜鸟教程所讲解的,类似API文档,它的作用在于,帮助你能看得懂shell脚本,提供编写一个shell脚本时,颗粒度最低的一种原料。
Introduction
当小编在github上遇到了来自澳大利亚工程师 Dylan Araps 所写的开源书籍《pure bash bible》时,虽然也是bash教程,但和《菜鸟教程》比较时,我总结了如下几点:
1.《菜鸟教程》适合刚入门bash的用户,提供类似api手册的功能。
2.《pure bash bible》适合有bash编写功底,基于特定场景介绍如何优雅地书写。
https://github.com/dylanaraps/pure-bash-bible
步入正题,如上提供了开源书籍的获取地址,目录如下:
应用实例
1)删除字符串中的所有的空白并用空格分割单词
这是sed
,awk
,perl
和其他工具的替代品。下面的函数通过重复使用单词拆分来创建一个没有前导/尾随空格的新字符串,并用空格分割字符串中的单词。
示例函数:
# shellcheck disable=SC2086,SC2048
trim_all() {
# Usage: trim_all " example string "
set -f
set -- $*
printf '%s\n' "$*"
set +f
}
用法示例:
$ trim_all " Hello, World "
Hello, World
$ name=" John Black is my name. "
$ trim_all "$name"
John Black is my name.
2)从字符串中删除所有正则实例
示例函数:
strip_all() {
# Usage: strip_all "string" "pattern"
printf '%s\n' "${1//$2}"
}
用法示例:
$ strip_all "The Quick Brown Fox" "[aeiou]"
Th Qck Brwn Fx
$ strip_all "The Quick Brown Fox" "[[:space:]]"
TheQuickBrownFox
$ strip_all "The Quick Brown Fox" "Quick "
The Brown Fox
更多使用技巧,请通过上述链接进入学习。
Translation
刚看到《pure-bash-bible》时,有冲动把这本书翻译过来,直至我打开了其中一个issue,有位小哥已经做了这件事儿了,点个赞!
https://github.com/A-BenMao/pure-bash-bible-zh_CN
AfterWord
Thanks for reading! If this bible helped you in any way and you'd like to give back, consider donating. Donations give me the time to make this the best resource possible. Can't donate? That's OK, star the repo and share it with your friends!
(捐赠地址:https://www.patreon.com/dyla)