歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Bash Getopts - 讓你的腳本支持命令行參數

Bash Getopts - 讓你的腳本支持命令行參數

日期:2017/2/28 14:30:44   编辑:Linux教程

以前我總想知道如何為我的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中是如何工作的,我認為不如直接來一個能工作的腳本更讓人覺得輕松一些。

  1. #!/bin/bash
  2. ######################################################################
  3. #This is an example of using getopts in Bash. It also contains some
  4. #other bits of code I find useful.
  5. #Author: Linerd
  6. #Website: http://tuxtweaks.com/
  7. #Copyright 2014
  8. #License: Creative Commons Attribution-ShareAlike 4.0
  9. #http://creativecommons.org/licenses/by-sa/4.0/legalcode
  10. ######################################################################
  11. #Set Script Name variable
  12. SCRIPT=`basename ${BASH_SOURCE[0]}`
  13. #Initialize variables to default values.
  14. OPT_A=A
  15. OPT_B=B
  16. OPT_C=C
  17. OPT_D=D
  18. #Set fonts for Help.[譯注: 這裡tput用來更改終端文本屬性,比如加粗,高亮等]
  19. NORM=`tput sgr0`
  20. BOLD=`tput bold`
  21. REV=`tput smso`
  22. #Help function
  23. function HELP {
  24. echo -e \\n"Help documentation for ${BOLD}${SCRIPT}.${NORM}"\\n
  25. echo -e "${REV}Basic usage:${NORM} ${BOLD}$SCRIPT file.ext${NORM}"\\n
  26. echo "Command line switches are optional. The following switches are recognized."
  27. echo "${REV}-a${NORM} --Sets the value for option ${BOLD}a${NORM}. Default is ${BOLD}A${NORM}."
  28. echo "${REV}-b${NORM} --Sets the value for option ${BOLD}b${NORM}. Default is ${BOLD}B${NORM}."
  29. echo "${REV}-c${NORM} --Sets the value for option ${BOLD}c${NORM}. Default is ${BOLD}C${NORM}."
  30. echo "${REV}-d${NORM} --Sets the value for option ${BOLD}d${NORM}. Default is ${BOLD}D${NORM}."
  31. echo -e "${REV}-h${NORM} --Displays this help message. No further functions are performed."\\n
  32. echo -e "Example: ${BOLD}$SCRIPT -a foo -b man -c chu -d bar file.ext${NORM}"\\n
  33. exit1
  34. }
  35. #Check the number of arguments. If none are passed, print help and exit.
  36. NUMARGS=$#
  37. echo -e \\n"Number of arguments: $NUMARGS"
  38. if[ $NUMARGS -eq 0];then
  39. HELP
  40. fi
  41. ### Start getopts code ###
  42. #Parse command line flags
  43. #如果選項需要後跟參數,在選項後面加":"
  44. #注意"-h"選項後面沒有":",因為他不需要參數。選項字符串最開始的":"是用來去掉來自getopts本身的報錯的,同時獲取不能識別的選項。(譯注:如果選項字符串不以":"開頭,發生錯誤(非法的選項或者缺少參數)時,getopts會向錯誤輸出打印錯誤信息;如果以":"開頭,則不會打印[在man中叫slient error reporting],同時將出錯的選項賦給OPTARG變量)
  45. while getopts :a:b:c:d:h FLAG;do
  46. case $FLAG in
  47. a)#set option "a"
  48. OPT_A=$OPTARG
  49. echo "-a used: $OPTARG"
  50. echo "OPT_A = $OPT_A"
  51. ;;
  52. b)#set option "b"
  53. OPT_B=$OPTARG
  54. echo "-b used: $OPTARG"
  55. echo "OPT_B = $OPT_B"
  56. ;;
  57. c)#set option "c"
  58. OPT_C=$OPTARG
  59. echo "-c used: $OPTARG"
  60. echo "OPT_C = $OPT_C"
  61. ;;
  62. d)#set option "d"
  63. OPT_D=$OPTARG
  64. echo "-d used: $OPTARG"
  65. echo "OPT_D = $OPT_D"
  66. ;;
  67. h)#show help
  68. HELP
  69. ;;
  70. \?)#unrecognized option - show help
  71. echo -e \\n"Option -${BOLD}$OPTARG${NORM} not allowed."
  72. HELP
  73. #在這裡如果你不想打印完整的幫助信息,只想顯示簡單的錯誤信息,去掉上面的兩行,同時使用下面的兩行。
  74. #echo -e "Use ${BOLD}$SCRIPT -h${NORM} to see the help documentation."\\n
  75. #exit 2
  76. ;;
  77. esac
  78. done
  79. shift $((OPTIND-1))#This tells getopts to move on to the next argument.
  80. ### End getopts code ###
  81. ### Main loop to process files ###
  82. #這裡你可以用你的腳本處理邏輯來替代。這個例子只是在終端中打印文件的文件���和後綴名。你可以把任意其他的文件處理任務放到這個while-do循環中。
  83. while[ $# -ne 0 ]; do
  84. FILE=$1
  85. TEMPFILE=`basename $FILE`
  86. #TEMPFILE="${FILE##*/}" #另外一種獲取不帶後綴的文件名的方法。
  87. FILE_BASE=`echo "${TEMPFILE%.*}"`#file without extension
  88. FILE_EXT="${TEMPFILE##*.}"#file extension
  89. echo -e \\n"Input file is: $FILE"
  90. echo "File withouth extension is: $FILE_BASE"
  91. echo -e "File extension is: $FILE_EXT"\\n
  92. shift #Move on to next input file.
  93. done
  94. ### End main loop ###
  95. exit0

將上面的代碼復制到你的文本編輯器裡,然後保存到你的可執行路徑下。我將這個腳本命名為 options 並保存到 /home/linerd/bin 路徑下。保存之後記得給你的腳本添加可執行權限。

  1. chmod +x ~/bin/options

現在腳本已經可以運行了。試試用 -h 參數來打印幫助信息吧。

  1. options -h

遇到不支持的選項,腳本同樣可以給出提示,並打印幫助信息。

  1. options -z

最後,getopts可以以任意的順序處理你給的命令行參數。唯一的限制是你要處理的文件必須放在所有參數的最後。

  1. options -d bar -c chu -b man -a foo example1.txt example2.txt

現在你可以從這些例子裡看到如何通過命令行參數給腳本裡的變量賦值。這個腳本裡除了getopts還有很多其他的東西,但是我認為這些就足以成為一個新腳本的開頭模板了。如果你有興趣更深入地學習bash的getopts,你可以找找深埋在man page的“Builtins”這一節裡的文檔,也可以從 Bash Reference Manual 找到信息。

接下來呢?

你會用getops來干什麼呢?在評論裡告訴我吧。

Copyright © Linux教程網 All Rights Reserved