Bash Getopts :讓你的腳本支持命令行參數(shù)
以前我總想知道如何為我的Bash腳本創(chuàng)建命令行參數(shù)。經(jīng)過搜索,我發(fā)現(xiàn)了2個(gè)函數(shù)可以處理這個(gè)問題,getopt 函數(shù)和 getopts 函數(shù)。我無意爭論哪一個(gè)函數(shù)更好的。getopts 是一個(gè)shell內(nèi)建命令,而且似乎比 getopt 更容易實(shí)現(xiàn)這個(gè)功能,所以在這篇文章里我準(zhǔn)備講講getopts。
bash getopts
開始的時(shí)候,我只試著處理傳遞給腳本的命令行參數(shù)。***,我添加了另外一些有用的功能函數(shù),使得這個(gè)腳本可以成為其他任何交互式腳本處理命令行的開始模板。我還添加了一個(gè)純文本格式的幫助函數(shù),讓腳本更加容易閱讀。
與其來一長段文字解釋 getopts 在bash中是如何工作的,我認(rèn)為不如直接來一個(gè)能工作的腳本更讓人覺得輕松一些。
- #!/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
- exit 1
- }
- #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
- #如果選項(xiàng)需要后跟參數(shù),在選項(xiàng)后面加":"
- #注意"-h"選項(xiàng)后面沒有":",因?yàn)樗恍枰獏?shù)。選項(xiàng)字符串最開始的":"是用來去掉來自getopts本身的報(bào)錯(cuò)的,同時(shí)獲取不能識(shí)別的選項(xiàng)。(譯注:如果選項(xiàng)字符串不以":"開頭,發(fā)生錯(cuò)誤(非法的選項(xiàng)或者缺少參數(shù))時(shí),getopts會(huì)向錯(cuò)誤輸出打印錯(cuò)誤信息;如果以":"開頭,則不會(huì)打印[在man中叫slient error reporting],同時(shí)將出錯(cuò)的選項(xiàng)賦給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
- #在這里如果你不想打印完整的幫助信息,只想顯示簡單的錯(cuò)誤信息,去掉上面的兩行,同時(shí)使用下面的兩行。
- #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 ###
- #這里你可以用你的腳本處理邏輯來替代。這個(gè)例子只是在終端中打印文件的文件名和后綴名。你可以把任意其他的文件處理任務(wù)放到這個(gè)while-do循環(huán)中。
- 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 ###
- exit 0
將上面的代碼復(fù)制到你的文本編輯器里,然后保存到你的可執(zhí)行路徑下。我將這個(gè)腳本命名為 options 并保存到/home/linerd/bin 路徑下。保存之后記得給你的腳本添加可執(zhí)行權(quán)限。
- chmod +x ~/bin/options
現(xiàn)在腳本已經(jīng)可以運(yùn)行了。試試用 -h 參數(shù)來打印幫助信息吧。
- options -h
遇到不支持的選項(xiàng),腳本同樣可以給出提示,并打印幫助信息。
- options -z
***,getopts可以以任意的順序處理你給的命令行參數(shù)。唯一的限制是你要處理的文件必須放在所有參數(shù)的***。
- options -d bar -c chu -b man -a foo example1.txt example2.txt
現(xiàn)在你可以從這些例子里看到如何通過命令行參數(shù)給腳本里的變量賦值。這個(gè)腳本里除了getopts還有很多其他的東西,但是我認(rèn)為這些就足以成為一個(gè)新腳本的開頭模板了。如果你有興趣更深入地學(xué)習(xí)bash的getopts,你可以找找深埋在man page的“Builtins”這一節(jié)里的文檔,也可以從 Bash Reference Manual 找到信息。
接下來呢?
你會(huì)用getops來干什么呢?在評(píng)論里告訴我吧。
via: http://tuxtweaks.com/2014/05/bash-getopts/
譯者: CNprober <travelwithheart@yeah.net, QQ619913541> 校對(duì):wxy