开源最前线(ID:OpenSourceTop) 综合整理
综合自:https://leanpub.com/u/dylanaraps、https://leanpub.com/u/dylanaraps
Bash脚本比我们想象中的都要强大,通过Bash脚本,大多数任务都可以让你在无任何其它语言或第三方依赖的安装环境下,快速写出脚本程序。
在Bash中调用外部进程是非常繁琐的,过度调用会导致明显的减速,通过内置方法编写的脚本和程序会更快,所需的依赖也会更少,并且帮助你更好的理解编程语言。
有位澳大利亚工的程师在Github上开源了一本书——《pure bash bible》
目前,这本书已经在Github上获得 24004 个Star,2005 个Fork(Github地址:https://github.com/dylanaraps/pure-bash-bible
本书收集汇总了编写 bash 脚本经常会使用到的一些代码片段,无论是常见和不太常见的方法都可以在这书里找到,通过书中的代码片段,可以删除脚本中的依赖项,并且在大多数情况下可以让程序运行的更快。
书中依照字符串、数组、正则表达式、文件处理、变量等脚本程序的常用功能进行分类,每个分类下都提供了具体 bash 代码实现。
删除字符串前后空格:
例如,下面的函数通过查找字符串前后空格字符,并把它们移除。以下为功能使用:
trim_string() {

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

"$_"
}

示例:
$ trim_string "    Hello,  World    "
Hello,  World


$
 name="   John Black  "
$ trim_string "$name"
John Black

在字符串上使用正则表达式:
regex() {

    # Usage: regex 
"string""regex"
[[ $1 =~ $2 ]]
 && printf 
%s

"${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

"${BASH_REMATCH[1]}"
else
printf
%s

"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

"${!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

完整代码片段请访问github
继续阅读
阅读原文