61

GitHub星数1.3W!五分钟带你搞定Bash脚本使用技巧

 4 years ago
source link: https://www.tuicool.com/articles/iIruaa2
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Bash脚本比我们想象中的都要强大,通过Bash脚本,大多数任务都可以让你在无任何其它语言或第三方依赖的安装环境下,快速写出脚本程序。

在Bash中调用外部进程是非常繁琐的,过度调用会导致明显的减速,通过内置方法编写的脚本和程序会更快,所需的依赖也会更少,并且帮助你更好的理解编程语言。

6vYn6v3.jpg!web

有位澳大利亚工的程师在Github上开源了一本书——《pure bash bible》

nuEz6bf.jpg!web

目前,这本书已经在Github上获得 13148 个Star,905 个Fork(Github地址:https://github.com/dylanaraps/pure-bash-bible)

本书收集汇总了编写 bash 脚本经常会使用到的一些代码片段,无论是常见和不太常见的方法都可以在这书里找到,通过书中的代码片段,可以删除脚本中的依赖项,并且在大多数情况下可以让程序运行的更快。

书中依照字符串、数组、正则表达式、文件处理、变量等脚本程序的常用功能进行分类,每个分类下都提供了具体 bash 代码实现。

删除字符串前后空格:

例如,下面的函数通过查找字符串前后空格字符,并把它们移除。以下为功能使用:

trim_string() { 
    # Usage: trim_string "   example   string    " 
    : "${1#"${1%%[![:space:]]*}"}" 
    : "${_%"${_##*[![:space:]]}"}" 
    printf '%s\n' "$_" 
} 

示例:

$ trim_string "    Hello,  World    " 
Hello,  World 
 
$ name="   John Black  " 
$ trim_string "$name" 
John Black 

在字符串上使用正则表达式:

regex() { 
    # Usage: regex "string" "regex" 
    [[ $1 =~ $2 ]] && printf '%s\n' "${BASH_REMATCH[1]}" 
} 

用法示例:

$ # Trim leading white-space. 
$ regex '    hello' '^\s*(.*)' 
hello 
 
$ # Validate a hex color. 
$ regex "#FFFFFF" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$' 
#FFFFFF 
 
$ # Validate a hex color (invalid). 
$ regex "red" '^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$' 
# no output (invalid) 

脚本的示例用法:

is_hex_color() { 
    if [[ $1 =~ ^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$ ]]; then 
        printf '%s\n' "${BASH_REMATCH[1]}" 
    else 
        printf '%s\n' "error: $1 is an invalid color." 
        return 1 
    fi 
} 
 
read -r color 
is_hex_color "$color" || color="#FFFFFF" 
 
# Do stuff. 

删除重复的数组:

remove_array_dups() { 
    # Usage: remove_array_dups "array" 
    declare -A tmp_array 
 
    for i in "$@"; do 
        [[ $i ]] && IFS=" " tmp_array["${i:- }"]=1 
    done 
 
    printf '%s\n' "${!tmp_array[@]}" 
} 

用法示例:

$ remove_array_dups 1 1 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 
1 
2 
3 
4 
5 
 
$ arr=(red red green blue blue) 
$ remove_array_dups "${arr[@]}" 
red 
green 
blue 

本书完整的脚本功能的代码片段如下:

uYjMniq.jpg!web

关于作者

a2IrI3A.jpg!web

Dylan Araps是来自澳大利亚墨尔本的开源开发人员,从小就对开源产生了极大的热情,多年来开源了许多项目,14岁,就离开了学校,开始专注于 Linux、编程和其他相关技能的学习,Dylan Araps开源的项目得到了广泛的应用,并在Unix和Linux社区中得到广泛关注。

开源最前线(ID:OpenSourceTop) 综合整理

综合自:https://leanpub.com/u/dylanaraps、https://leanpub.com/u/dylanaraps


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK