[email protected]Mon – Fri 9:00AM – 5:00PMLinkedInXFacebook
NexonHost
Netherlands Dedicated ServersAmsterdam · Equinix AM6Germany Dedicated ServersFrankfurt · Equinix FR4Romania Dedicated ServersBucharest · VoxilityAustria Dedicated ServersVienna · Interxion VIEBulgaria Dedicated ServersSofia · TelepointFrance Dedicated ServersParis · Interxion PAR — Marseille · Digital Realty MRS3Ireland Dedicated ServersDublin · Equinix DB2Italy Dedicated ServersMilan · Irideos AvalonPoland Dedicated ServersWarsawSpain Dedicated ServersMadrid · Equinix MD2United States Dedicated ServersAshburn · Equinix DC
All articles
Knowledge BaseSeptember 15, 2023

How to use getopts command in Linux.

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:

while getopts options opt; do
  case $opt in
    # Handle each option here
  esac
done
  • 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:

./myscript.sh -a -b arg1 -c arg2

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:

case $opt in
  a)
    # Handle option -a
    ;;
  b)
    # Handle option -b with argument $OPTARG
    ;;
  c)
    # Handle option -c with argument $OPTARG
    ;;
  \?)
    # Handle unrecognized options
    ;;
  :)
    # Handle options that require an argument missing the argument
    ;;
esac
  • 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.

 

Practical Example

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:

#!/bin/bash

while getopts "i:o:" opt; do
  case $opt in
    i)
      input_dir=$OPTARG
      ;;
    o)
      output_dir=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

# Perform backup using the provided input and output directories
echo "Backing up $input_dir to $output_dir"
# Add your backup logic here

Users can now run your script like this:

./backup.sh -i /path/to/source -o /path/to/backup

By using getopts, you’ve made your script more user-friendly, allowing users to easily specify input and output directories.

 

Conclusion

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.

Keep reading
How to Implement Network Segmentation and Resource Isolation in Linux.
February 6, 2024

How to Implement Network Segmentation and Resource Isolation in Linux.

How to Implement Network Segmentation and Resource Isolation in Linux. Securing and managing networks in a Linux environment involves advanced practices like network segmentation and resource isolation. This guide explores these concepts, providing detailed instructions and examples for…

Read article
How to open or close ports in Linux.
February 6, 2024

How to open or close ports in Linux.

How to open or close ports in Linux. Effectively managing ports on your Linux system is crucial for both security and service accessibility. This comprehensive guide will provide a detailed walkthrough on opening and closing ports using the robust tools iptables and ufw. Understanding these…

Read article
How to use ypdomainname command.
January 23, 2024

How to use ypdomainname command.

How to use ypdomainname command. In the realm of Linux networking, the ypdomainname command plays a crucial role in the context of the Network Information Service (NIS). NIS, formerly known as Yellow Pages, is a distributed database service that facilitates the sharing of network configuration and…

Read article
Get in Touch

Together, Let’s Build a Faster, Safer Internet.

Build scalable infrastructure with NexonHost — high-performance dedicated servers, VPS hosting, colocation, and DDoS protection across Europe.

Get Started →Contact Us
[email protected]Mon – Fri 9:00AM – 5:00PM