Bash Getopts-Allow your script to support command line parameters

Source: Internet
Author: User
Tags creative commons attribution

Bash Getopts-Allow your script to support command line parameters

In the past, I always wanted to know how to create command line parameters for my Bash script. After searching, I found two functions that can solve this problem: the getopt function and the getopts function. I have no intention of arguing which function is better. Getopts is a shell built-in command, and it seems easier to implement this function than getopt. So in this article, I am going to talk about getopts.

Bash script 15-minute advanced tutorial

Job control instances of Bash and KSH shell in 10 Linux/Unix

Abnormal shell script running in Ubuntu: difference between Bash and dash

Bash script for statement if statement and various test statements

What is the Bash Shell build in command?

Bash getopts

At the beginning, I only tried to process the command line parameters passed to the script. Finally, I added some other useful function functions so that this script can become the starting template for any other interactive script to process command lines. I also added a help function in plain text format to make the script easier to read.

Instead of explaining how getopts works in bash with a long text segment, I think it is easier to directly use a working script.

  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-submit alike 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 =
  15. OPT_ B = B
  16. OPT_C = C
  17. OPT_D = D
  18. # Set fonts for Help. [Note: Here tput is used to change terminal text attributes, such as bold and highlighted]
  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 saved med." \ 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. # If the option needs to be followed by a parameter, add ":" To the option ":"
  44. # Note that the "-h" option is not followed by ":", because it does not require a parameter. The option string ":" is used to remove the error from getopts and obtain unrecognized options. If the option string does not start with ":" and an error (invalid option or missing parameter) occurs, getopts will print the error message to the error ": ", it will not print [slient error reporting in man], and assign the error option to the OPTARG variable)
  45. While getopts: a: B: c: d: h FLAG; do
  46. Case $ FLAG in
  47. A) # set option ""
  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. # If you do not want to print the complete help information here, you only want to display simple error information, remove the above two rows, and use the following two rows at the same time.
  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. # Here you can use your script processing logic to replace it. This example only prints the file name and Suffix in the terminal. You can place any other file processing tasks in this while-do loop.
  83. While [$ #-ne 0]; do
  84. FILE = $1
  85. TEMPFILE = 'basename $ file'
  86. # TEMPFILE = "$ {FILE ### */}" # Another method to obtain a FILE name without a suffix.
  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

Copy the above Code to your text editor and save it to your executable path. I name this script as options and save it to the/home/linerd/bin path. After saving the script, remember to add executable permissions to your script.

  1. Chmod + x ~ /Bin/options

Now the script can be run. Use the-h parameter to print the help information.

  1. Options-h

If an unsupported option is encountered, the script can also give a prompt and print the help information.

  1. Options-z

Finally, getopts can process your command line parameters in any order. The only restriction is that the file to be processed must be placed at the end of all parameters.

  1. Options-d bar-c chu-B man-a foo example1.txt example2.txt

Now you can see from these examples how to assign values to variables in the script using command line parameters. In addition to getopts, there are many other things in this script, but I think this is enough to become the starting template of a new script. If you are interested in learning bash's getopts in more depth, you can find the document deep in the "Builtins" section of man page, or find information from Bash Reference Manual.

What about next?

What will you do with getops? Let me know in the comment.

This article permanently updates the link address:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.