Hero Image
進階 Shell 腳本技巧:用 Bash 自動化複雜任務

進階 Shell 腳本技巧:用 Bash 自動化複雜任務 使用內建指令 內建指令執行更快,因為不需要載入外部程序。 減少子殼層 子殼層會帶來效能成本。 # Inefficient output=$(cat file.txt) # Efficient output=$(<file.txt) 使用陣列處理大量資料 處理大量資料時,陣列比多個變數更有效率,也更好管理。 # Inefficient item1="apple" item2="banana" item3="cherry" # Efficient items=("apple" "banana" "cherry") for item in "${items[@]}"; do echo "$item" done 啟用 Noclobber 避免檔案被意外覆寫。 set -o noclobber 使用函式 函式可以封裝並重用程式碼,讓腳本更乾淨、重複更少。 高效的檔案操作 進行檔案操作時,使用更有效率的技巧以降低資源消耗。 # Inefficient while read -r line; do echo "$line" done < file.txt # Efficient while IFS= read -r line; do echo "$line" done < file.txt 平行處理 像 xargs 和 GNU parallel 這類工具非常實用。 錯誤處理 健全的錯誤處理對建立可靠、易維護的腳本至關重要。 # Exit on Error: Using set -e ensures that your script exits immediately if any command fails, preventing cascading errors. set -e # Custom Error Messages: Implement custom error messages to provide more context when something goes wrong. command1 || { echo "command1 failed"; exit 1; } # Trap Signals: Use the `trap` command to catch and handle signals and errors gracefully. trap 'echo "Error occurred"; cleanup; exit 1' ERR function cleanup() { # Cleanup code } # Validate Inputs: Always validate user inputs and script arguments to prevent unexpected behavior. if [[ -z "$1" ]]; then echo "Usage: $0 <argument>" exit 1 fi # Logging: Implement logging to keep track of script execution and diagnose issues. logfile="script.log" exec > >(tee -i $logfile) exec 2>&1 echo "Script started" 自動化複雜的系統管理工作 自動化備份 系統監控 使用者管理 自動更新 網路設定

Hero Image
Go 文章

學會 gin 參數校驗之 validator 函式庫,看這一篇就夠了 字串約束 excludesall:不包含參數中任意的 UNICODE 字元,例如 excludesall=ab excludesrune:不包含參數表示的 rune 字元,excludesrune=asong startswith:以參數子字串為前綴,例如 startswith=hi endswith:以參數子字串為後綴,例如 endswith=bye。 contains=:包含參數子字串,例如 contains=email containsany:包含參數中任意的 UNICODE 字元,例如 containsany=ab containsrune:包含參數表示的 rune 字元,例如 containsrune=asong excludes:不包含參數子字串,例如 excludes=email 範圍約束 範圍約束的欄位型別分為三種: 對於數值,我們可以約束其值 對於切片、陣列和 map,我們可以約束其長度 對於字串,我們可以約束其長度 常用 tag 介紹: ne:不等於參數值,例如 ne=5 gt:大於參數值,例如 gt=5 gte:大於等於參數值,例如 gte=50 lt:小於參數值,例如 lt=50 lte:小於等於參數值,例如 lte=50 oneof:只能是列舉出的值其中之一,這些值必須是數值或字串,以空格分隔;如果字串中有空格,請用單引號包起來,例如 oneof=male female。 eq:等於參數值,注意與 len 不同。對於字串,eq 約束字串本身的值,而 len 約束字串長度。例如 eq=10 len:等於參數值,例如 len=10 max:小於等於參數值,例如 max=10 min:大於等於參數值,例如 min=10 欄位約束 eqfield:定義欄位間相等約束,用於約束同一結構體中的欄位。例如:eqfield=Password eqcsfield:約束同一結構體中欄位等於另一個欄位(相對),確認密碼時可以使用,例如:eqcsfield=ConfirmPassword nefield:用來約束兩個欄位是否不同,確認兩種顏色是否一致時可以使用,例如:nefield=Color1 necsfield:約束兩個欄位是否不同(相對) 常用約束 unique:指定唯一性約束,不同型別處理不同: