How To Use Getopts Command.
Shell scripting is a powerful way to automate tasks and create custom utilities in Unix-like operating systems such as Linux. When writing shell scripts, it’s common to need to process command-line arguments and options provided by users. The getopts command is a fundamental tool for handling these command-line arguments efficiently. In this article, we will explore what getopts is, how it works, and how you can use it to enhance your shell scripts.
What is getopts?
getopts is a built-in shell command that allows you to parse command-line options (flags) and their associated arguments. It is particularly useful when you want to add flexibility and user-friendliness to your shell scripts by allowing users to customize the behavior of your script through command-line options.
How Does getopts Work?
getopts processes the command-line arguments passed to a shell script using a specified format. The basic syntax for getopts is as follows:
options is a string containing the valid option letters your script should recognize. If an option letter is followed by a colon (e.g., a:b), it indicates that the option requires an argument.
opt is a variable that stores the currently processed option.
Within the while loop, getopts reads and processes each option and argument in turn. For example, if your script is called myscript.sh and you run it with the following command:
getopts will process each option (-a, -b, -c) and their respective arguments (arg1, arg2).
Handling Options with case Statements
Inside the case statement within the getopts loop, you can define how your script should respond to each recognized option. For example:
Use a) for handling option -a.
Use b) for handling option -b, with the associated argument stored in the $OPTARG variable.
Use c) for handling option -c, also with its argument in $OPTARG.
Use \?) for handling unrecognized options.
Use 🙂 for handling options that require an argument but have a missing argument.
Let’s put getopts to use in a practical example. Suppose you want to create a script called backup.sh that allows users to specify a backup directory and an output location. Here’s a basic implementation:
Users can now run your script like this:
By using getopts, you’ve made your script more user-friendly, allowing users to easily specify input and output directories.
getopts is a valuable tool for processing command-line arguments in shell scripts. It allows you to define options and their associated arguments, making your scripts more interactive and versatile. By using getopts, you can create scripts that are more user-friendly and powerful, enhancing your ability to automate tasks and perform system administration tasks efficiently in Unix-like environments.