How to Get Arguments with Flags in Bash


Bash, the default shell for most Unix-based operating systems, provides a powerful set of tools and functionalities for automating tasks and managing system resources. One of the essential features of Bash is the ability to pass arguments to scripts or commands through the use of flags.

Flags enable you to customize and control the behavior of your scripts, making them more versatile and efficient. In this article, we will explore the art of working with arguments and flags in Bash, guiding you through the process step by step.

Getting Arguments with Flags in Bash

If you want to retrieve arguments with flags in Bash, you have the option to utilize the “getopts” command. This command is an inherent function in Bash that enables you to parse command-line options and arguments effectively. When using “getopts,” you need to provide three arguments: the option string, the variable to hold the current option, and the variable name for storing the remaining arguments. Consider the following example to better understand its implementation:

#!/bin/bash

while getopts ":a:b:" opt; do

 case $opt in

 a)

 first_arg="$OPTARG"

 ;;

 b)

 second_arg="$OPTARG"

 ;;

 \?)

 echo "Invalid: -$OPTARG" >&2

 ;;

 :)

 echo "Option -$OPTARG requires an argument." >&2

 ;;

 esac

done

shift $((OPTIND-1))

echo "First Argument : $first_arg"

echo "Second Argument : $second_arg"

The code starts by defining a while loop with the “getopts” command, followed by a colon (:) to specify the available options, in this case, “a” and “b”. Inside the loop, the script utilizes the “case” statement to handle each option accordingly.

If the script encounters the “-a” flag, it assigns the value of the corresponding argument to the variable “first_arg”. Similarly, if the “-b” flag is encountered, the script assigns the argument value to the variable “second_arg”. If an invalid option is provided, the script outputs an error message indicating the invalid flag. If an option requires an argument, but none is provided, the script displays an error message specifying the missing argument.

After parsing all the options, the script uses the “shift” command to remove the processed options from the command-line arguments. Finally, it outputs the values of “first_arg” and “second_arg” to demonstrate the successful retrieval of the provided arguments with flags.

sudo bash<name-of-script-file> -<flag1> <first-argument> -<flag2> <second-argument>

 

A screenshot of a computer Description automatically generated

Conclusion

Utilizing flags to pass optional arguments to Bash scripts can greatly enhance their flexibility and functionality. With the “getopts” command, parsing command-line options and arguments becomes a seamless process. By referring to the example presented in this article, you can effortlessly incorporate flags into your own Bash scripts and effectively manage them.

Print Friendly, PDF & Email
Categories

2 Comments

Add yours
  1. 1
    MikeL

    I’ve commented in LinkedIn:
    ”’
    # Defaults –
    PROGNAME=$0
    CMD=$PWD
    # Usage
    usage() {
    cat <&2
    `tput setaf 5`””`tput setaf 7`
    Usage: $PROGNAME `tput setaf 2`-a `tput setaf 1` `tput setaf 2`-b `tput setaf 1`
    This awesome examples creates usage/help, and uses the 2 arguments

    `tput setaf 2`-a `tput setaf 7`: `tput setaf 2`Description of arg a [default: ${MY_ARG_A}]
    `tput setaf 2`-b `tput setaf 7`: `tput setaf 2`Description of Arg B [default: ${MY_ARG_B}]
    `tput setaf 6`Example: $PROGNAME -a myawesomestring -b myawesomeargb
    `tput setaf 7`
    EOF
    exit 1
    }
    # Default Variables
    MY_ARG_A=”My string A”
    MY_ARG_B=”My Arg B whatever”
    while getopts a:b:h o; do
    case $o in
    (c) MY_ARG_A=$OPTARG;;
    (p) MY_ARG_B=$OPTARG;;
    (*) usage
    esac
    done
    shift “$((OPTIND – 1))”

    # Verify
    # Various methods to verify if these have values like – if [ -z $MY_ARG_A], or with other methods of file paths, their existence – if [ !-f $MY_ARG_B] and call the usage function with a text describing what’s missing:
    # e.g.
    if [ ! -f $MY_ARG_B] ; then
    usage “Verify the provided path exists and try again: arguments are provided: my_arg_b:$MY_ARG_B
    exit 1
    fi
    #The code….
    echo “ArgA: ${MY_ARG_A}”
    echo “ArgB: ${MY_ARG_B}”

    #The End

    I haven’t tested it as it is, just to comment with more options since when we create arguments, especially for widely used scripts become everyday tools and these are also shared with others, so having these with help to collaborate and share

  2. 2
    james kent

    Just add these lines of code to display the help message in case the user doesn’t know what’s missing while running the script : ”
    # Usage
    usage() {
    if [[ $# -eq 0 ]]; then
    cat <&2
    Usage: $PROGNAME [options]
    This awesome example creates usage/help, and uses the 2 arguments
    -a Description of arg a [default: ${MY_ARG_A}]
    -b Description of Arg B [default: ${MY_ARG_B}]
    Example: $PROGNAME -a myawesomestring -b myawesomeargb
    EOF
    fi
    exit 1
    }”
    and call this function using this condition ”
    if [[ $# -ne 2 ]]; then
    echo “Expected 2 arguments, got $#”; usage;
    fi”

Comments are closed.