以前我總想知道如何為我的Bash腳本創建命令行參數。經過搜索,我發現了2個函數可以處理這個問題,getopt 函數和 getopts 函數。我無意爭論哪一個函數更好的。getopts 是一個shell內建命令,而且似乎比 getopt 更容易實現這個功能,所以在這篇文章裡我准備講講getopts。
Bash腳本15分鐘進階教程 http://www.linuxidc.com/Linux/2014-04/100750.htm
10個 Linux/Unix下 Bash 和 KSH shell 的作業控制實例 http://www.linuxidc.com/Linux/2014-03/98159.htm
Ubuntu下shell腳本運行異常:Bash和dash的區別 http://www.linuxidc.com/Linux/2013-10/91100.htm
Bash腳本之for語句if語句以及各種測試語句 http://www.linuxidc.com/Linux/2013-07/87922.htm
什麼是Bash Shell的內建(build in)命令 http://www.linuxidc.com/Linux/2013-06/86039.htm
bash getopts
開始的時候,我只試著處理傳遞給腳本的命令行參數。最後,我添加了另外一些有用的功能函數,使得這個腳本可以成為其他任何交互式腳本處理命令行的開始模板。我還添加了一個純文本格式的幫助函數,讓腳本更加容易閱讀。
與其來一長段文字解釋 getopts 在bash中是如何工作的,我認為不如直接來一個能工作的腳本更讓人覺得輕松一些。
- #!/bin/bash
- ######################################################################
- #This is an example of using getopts in Bash. It also contains some
- #other bits of code I find useful.
- #Author: Linerd
- #Website: http://tuxtweaks.com/
- #Copyright 2014
- #License: Creative Commons Attribution-ShareAlike 4.0
- #http://creativecommons.org/licenses/by-sa/4.0/legalcode
- ######################################################################
- #Set Script Name variable
- SCRIPT=`basename ${BASH_SOURCE[0]}`
- #Initialize variables to default values.
- OPT_A=A
- OPT_B=B
- OPT_C=C
- OPT_D=D
- #Set fonts for Help.[譯注: 這裡tput用來更改終端文本屬性,比如加粗,高亮等]
- NORM=`tput sgr0`
- BOLD=`tput bold`
- REV=`tput smso`
- #Help function
- function HELP {
- echo -e \\n"Help documentation for ${BOLD}${SCRIPT}.${NORM}"\\n
- echo -e "${REV}Basic usage:${NORM} ${BOLD}$SCRIPT file.ext${NORM}"\\n
- echo "Command line switches are optional. The following switches are recognized."
- echo "${REV}-a${NORM} --Sets the value for option ${BOLD}a${NORM}. Default is ${BOLD}A${NORM}."
- echo "${REV}-b${NORM} --Sets the value for option ${BOLD}b${NORM}. Default is ${BOLD}B${NORM}."
- echo "${REV}-c${NORM} --Sets the value for option ${BOLD}c${NORM}. Default is ${BOLD}C${NORM}."
- echo "${REV}-d${NORM} --Sets the value for option ${BOLD}d${NORM}. Default is ${BOLD}D${NORM}."
- echo -e "${REV}-h${NORM} --Displays this help message. No further functions are performed."\\n
- echo -e "Example: ${BOLD}$SCRIPT -a foo -b man -c chu -d bar file.ext${NORM}"\\n
- exit1
- }
- #Check the number of arguments. If none are passed, print help and exit.
- NUMARGS=$#
- echo -e \\n"Number of arguments: $NUMARGS"
- if[ $NUMARGS -eq 0];then
- HELP
- fi
- ### Start getopts code ###
- #Parse command line flags
- #如果選項需要後跟參數,在選項後面加":"
- #注意"-h"選項後面沒有":",因為他不需要參數。選項字符串最開始的":"是用來去掉來自getopts本身的報錯的,同時獲取不能識別的選項。(譯注:如果選項字符串不以":"開頭,發生錯誤(非法的選項或者缺少參數)時,getopts會向錯誤輸出打印錯誤信息;如果以":"開頭,則不會打印[在man中叫slient error reporting],同時將出錯的選項賦給OPTARG變量)
- while getopts :a:b:c:d:h FLAG;do
- case $FLAG in
- a)#set option "a"
- OPT_A=$OPTARG
- echo "-a used: $OPTARG"
- echo "OPT_A = $OPT_A"
- ;;
- b)#set option "b"
- OPT_B=$OPTARG
- echo "-b used: $OPTARG"
- echo "OPT_B = $OPT_B"
- ;;
- c)#set option "c"
- OPT_C=$OPTARG
- echo "-c used: $OPTARG"
- echo "OPT_C = $OPT_C"
- ;;
- d)#set option "d"
- OPT_D=$OPTARG
- echo "-d used: $OPTARG"
- echo "OPT_D = $OPT_D"
- ;;
- h)#show help
- HELP
- ;;
- \?)#unrecognized option - show help
- echo -e \\n"Option -${BOLD}$OPTARG${NORM} not allowed."
- HELP
- #在這裡如果你不想打印完整的幫助信息,只想顯示簡單的錯誤信息,去掉上面的兩行,同時使用下面的兩行。
- #echo -e "Use ${BOLD}$SCRIPT -h${NORM} to see the help documentation."\\n
- #exit 2
- ;;
- esac
- done
- shift $((OPTIND-1))#This tells getopts to move on to the next argument.
- ### End getopts code ###
- ### Main loop to process files ###
- #這裡你可以用你的腳本處理邏輯來替代。這個例子只是在終端中打印文件的文件���和後綴名。你可以把任意其他的文件處理任務放到這個while-do循環中。
- while[ $# -ne 0 ]; do
- FILE=$1
- TEMPFILE=`basename $FILE`
- #TEMPFILE="${FILE##*/}" #另外一種獲取不帶後綴的文件名的方法。
- FILE_BASE=`echo "${TEMPFILE%.*}"`#file without extension
- FILE_EXT="${TEMPFILE##*.}"#file extension
- echo -e \\n"Input file is: $FILE"
- echo "File withouth extension is: $FILE_BASE"
- echo -e "File extension is: $FILE_EXT"\\n
- shift #Move on to next input file.
- done
- ### End main loop ###
- exit0
將上面的代碼復制到你的文本編輯器裡,然後保存到你的可執行路徑下。我將這個腳本命名為 options 並保存到 /home/linerd/bin 路徑下。保存之後記得給你的腳本添加可執行權限。
- chmod +x ~/bin/options
現在腳本已經可以運行了。試試用 -h 參數來打印幫助信息吧。
- options -h
遇到不支持的選項,腳本同樣可以給出提示,並打印幫助信息。
- options -z
最後,getopts可以以任意的順序處理你給的命令行參數。唯一的限制是你要處理的文件必須放在所有參數的最後。
- options -d bar -c chu -b man -a foo example1.txt example2.txt
現在你可以從這些例子裡看到如何通過命令行參數給腳本裡的變量賦值。這個腳本裡除了getopts還有很多其他的東西,但是我認為這些就足以成為一個新腳本的開頭模板了。如果你有興趣更深入地學習bash的getopts,你可以找找深埋在man page的“Builtins”這一節裡的文檔,也可以從 Bash Reference Manual 找到信息。
接下來呢?
你會用getops來干什麼呢?在評論裡告訴我吧。