[email protected]Support 24/7 · Billing 09:00 – 00:00LinkedInXFacebook
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 Copy Files and Directories.
May 10, 2023

How to Copy Files and Directories.

How To Copy Files And Directories. It is common practice to use the cp command to copy files and rsync to copy directories. Copying files and directories is one of the most common tasks you’ll perform when working on the command line. There are several commands for copying files in Linux, with cp…

Read article
How to Clear (Flush) the DNS Cache on Windows, MacOS, and Linux
May 10, 2023

How to Clear (Flush) the DNS Cache on Windows, MacOS, and Linux

How To Clear (Flush) The DNS Cache On Windows, MacOS, And Linux This article provides instructions on how to flush the DNS cache on different operating systems and web browsers. DNS cache is a temporary database that stores information about previous DNS lookups. In other words, whenever you visit…

Read article
How to use Xargs Command.
May 9, 2023

How to use Xargs Command.

How To Use Xargs Command. In this tutorial, we’ll cover the basics of using the xargs command. The xargs utility allows you to build and execute commands from standard input. It is usually used in combination with other commands through piping. With xargs, you can provide standard input as…

Read article
Get in Touch

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

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

Get Started →Contact Us
[email protected]Support 24/7 · Billing 09:00 – 00:00