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.
Comments ( 0 )
No comments available