Example No. 2
做爲shell編寫人員,常常面對數據格式不一致的問題,將數據標準話後輸出是一個須要解決問題,本示例以MySQL的時間爲例,腳本輸入月、日、年三個參數,將其標準化後輸出,月份以英文標準輸出,年份若是是4個數字,直接輸出,若是是0~69,則年份爲2000~2069,若是是70~99,則年份爲1970~1999;
腳本示例:git
#!/bin/bash #shell name:shell_format.sh #author by woon #數據標準化輸出示例 Month_to_name() { case $1 in 1 ) month="Jan" ;; 2 ) month="Feb" ;; 3 ) month="Mar" ;; 4 ) month="Apr" ;; 5 ) month="May" ;; 6 ) month="Jun" ;; 7 ) month="Jul" ;; 8 ) month="Aug" ;; 9 ) month="Sep" ;; 10) month="Oct" ;; 11) month="Nov" ;; 12) month="Dec" ;; * ) echo "$0: 錯誤的月份格式:$1" >&2; exit 1 esac return 0 } #腳本主體 if [ $# -ne 3 ]; then echo "Usage: $0 month day year\nThe correct formats are 8 21 2018 or August 21 2018" exit 1 fi #判斷年份是不是數字,並拼接年份 #判斷是不是個位數 if [ -z $(echo $3 | sed 's/^[0-9]//g') ];then year=200$3 #判斷是不是10-69之間數字 elif [ -z $(echo $3 | sed 's/^[1-6][0-9]//g') ]; then year=20$3 elif [ -z $(echo $3 | sed s'/^[7-9][0-9]//g') ]; then year=19$3 elif [ -z $(echo $3 | sed 's/^[0-9]\{4\}//g') ]; then year=$3 else echo "The yeat's formats are wrong:$3" exit 2 fi #腳本主體 if [ -z $(echo $1 | sed 's/[[:digit:]]//g') ]; then Month_to_name $1 else month=$(${$1%${$1#?}}|tr '[a-z]' '[A-Z]')$(echo $1|cut -c2-3 | tr '[A-Z' '[a-z]') fi echo $month $2 $year exit 0
運行結果:shell