GitHub星數(shù)1.3W!五分鐘帶你搞定Bash腳本使用技巧
Bash腳本比我們想象中的都要強大,通過Bash腳本,大多數(shù)任務(wù)都可以讓你在無任何其它語言或第三方依賴的安裝環(huán)境下,快速寫出腳本程序。
在Bash中調(diào)用外部進(jìn)程是非常繁瑣的,過度調(diào)用會導(dǎo)致明顯的減速,通過內(nèi)置方法編寫的腳本和程序會更快,所需的依賴也會更少,并且?guī)椭愀玫睦斫饩幊陶Z言。
有位澳大利亞工的程師在Github上開源了一本書——《pure bash bible》
目前,這本書已經(jīng)在Github上獲得 13148 個Star,905 個Fork(Github地址:https://github.com/dylanaraps/pure-bash-bible)
本書收集匯總了編寫 bash 腳本經(jīng)常會使用到的一些代碼片段,無論是常見和不太常見的方法都可以在這書里找到,通過書中的代碼片段,可以刪除腳本中的依賴項,并且在大多數(shù)情況下可以讓程序運行的更快。
書中依照字符串、數(shù)組、正則表達(dá)式、文件處理、變量等腳本程序的常用功能進(jìn)行分類,每個分類下都提供了具體 bash 代碼實現(xiàn)。
刪除字符串前后空格:
例如,下面的函數(shù)通過查找字符串前后空格字符,并把它們移除。以下為功能使用:
- 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
在字符串上使用正則表達(dá)式:
- 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.
刪除重復(fù)的數(shù)組:
- 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
本書完整的腳本功能的代碼片段如下:
關(guān)于作者
Dylan Araps是來自澳大利亞墨爾本的開源開發(fā)人員,從小就對開源產(chǎn)生了極大的熱情,多年來開源了許多項目,14歲,就離開了學(xué)校,開始專注于 Linux、編程和其他相關(guān)技能的學(xué)習(xí),Dylan Araps開源的項目得到了廣泛的應(yīng)用,并在Unix和Linux社區(qū)中得到廣泛關(guān)注。
開源最前線(ID:OpenSourceTop) 綜合整理
綜合自:https://leanpub.com/u/dylanaraps、https://leanpub.com/u/dylanaraps