How to validate unsupported Flags on Bash Script on Ubuntu 22.04

To validate unsupported Flags on Bash Script on Ubuntu 22.04

Introduction

Flags, also known as command-line options, are additional parameters passed to a script when it is executed. They modify the script's behaviour or specify certain settings. These flags are usually single-character letters preceded by a hyphen.

Procedure

Step – 1 : At first, check the OS version

root@linuxhelp:~# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 22.04.3 LTS
Release:        22.04
Codename:       jammy

Step – 2 : Now create a file using the vim editor

root@linuxhelp:~# vim unsupported_flags.sh
Add the following lines
#!/bin/bash
flag1="false"
flag2="false"
year=2001
number=42
while getopts "y:n:1:2" OPT; do
    case "$OPT" in
        y)
            year=${OPTARG}
            ;;
        n)
            number=${OPTARG}
            ;;
        1)
            flag1="true"
            ;;
        2)
            flag2="true"
            ;;
        ?)
            echo "Usage: $0 [-y year] [-n number] [-1|-2]" >&2
            exit 1
            ;;
    esac
done
#shift
if $flag1 -eq 0 && $flag2 -eq 0 ; then
    echo "$0: The options -1 and -2 cannot be specified together." >&2
    exit 1
fi
echo "$year"
echo "$number"
echo "$flag1"
echo "$flag2"

Step – 3 : Give the execute permission to the file

root@linuxhelp:~# chmod +x unsupported_flags.sh

Step – 4 : Now run the scrit with no flags

root@linuxhelp:~# ./unsupported_flags.sh
2001
42
false
false

Step – 5 : Again run the script with both flags

root@linuxhelp:~# ./unsupported_flags.sh -1 20 -2 40
./unsupported_flags.sh: The options -1 and -2 cannot be specified together.

Step – 6 : Now run the script with any one flag

root@linuxhelp:~# ./unsupported_flags.sh -1 20
2001
42
true
false

Conclusion :

We have reached the end of this article. In this guide, we have walked you through the steps required to Validate Unsupported Flags on Bash Script on Ubuntu 22.04. Your feedback is much welcome.

FAQ
Q
How do you handle flags in Bash script?
A
Flags are typically prefixed with a hyphen - for short options or two hyphens -- for long options.
Q
How do I give multiple arguments in bash?
A
You can pass more than one argument to your bash script. In general, here is the syntax of passing multiple arguments to any bash script: script.sh arg1 arg2 arg3
Q
What is $? In bash script?
A
The $? variable holds the exit status of a command, a function, or of the script itself.
Q
How do you handle arguments in a bash script?
A
We can use the getopts program/ command to parse the arguments passed to the script in the command line/ terminal by using loops and switch-case statements.
Q
What are $1 and $2 in the Bash script?
A
$0 - The name of the script. $1 - The first argument sent to the script. $2 - The second argument sent to the script.