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.
- #! /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-submit alike 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 =
- OPT_ B = B
- OPT_C = C
- OPT_D = D
- # Set fonts for Help. [Note: Here tput is used to change terminal text attributes, such as bold and highlighted]
- 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 saved med." \ 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
- # If the option needs to be followed by a parameter, add ":" To the option ":"
- # 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)
- While getopts: a: B: c: d: h FLAG; do
- Case $ FLAG in
- A) # set option ""
- 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
- # 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.
- # 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 ###
- # 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.
- While [$ #-ne 0]; do
- FILE = $1
- TEMPFILE = 'basename $ file'
- # TEMPFILE = "$ {FILE ### */}" # Another method to obtain a FILE name without a suffix.
- 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
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.
- Chmod + x ~ /Bin/options
Now the script can be run. Use the-h parameter to print the help information.
- Options-h
If an unsupported option is encountered, the script can also give a prompt and print the help information.
- 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.
- 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: