副问题[/!--empirenews.page--]
Bash剧本比我们想象中的都要强盛,通过Bash剧本,大大都使命都可以让你在无任何其余说话或第三方依靠的安装情形下,快速写出剧本措施。
在Bash中挪用外部历程长短常繁琐的,太过挪用会导致明明的减速,通过内置要领编写的剧本和措施会更快,所需的依靠也会更少,而且辅佐你更好的领略编程说话。

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

今朝,这本书已经在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 '%sn' "$_"
- }
示例:
- $ trim_string " Hello, World "
- Hello, World
-
- $ name=" John Black "
- $ trim_string "$name"
- John Black
在字符串上行使正则表达式:
- regex() {
- # Usage: regex "string" "regex"
- [[ $1 =~ $2 ]] && printf '%sn' "${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 '%sn' "${BASH_REMATCH[1]}"
- else
- printf '%sn' "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 '%sn' "${!tmp_array[@]}"
- }
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|