How to pass Multiple Arguments to Multiple Flags on Bash Script
To Pass Multiple Arguments to Multiple Flags on Bash Script
Introduction
When developing a bash script, it is important to facilitate user interaction by allowing the inclusion of specific options or arguments. This can be accomplished in bash by utilizing flags or options. A flag is typically represented as a single character or a word that begins with a hyphen (-) and is employed to indicate a particular behavior or option.
Procedure
Step1: Check the OS-version
[root@linuxhelp ~]# cat /etc/os-release
NAME="Oracle Linux Server"
VERSION="9.4"
ID="ol"
ID_LIKE="fedora"
VARIANT="Server"
VARIANT_ID="server"
VERSION_ID="9.4"
PLATFORM_ID="platform:el9"
PRETTY_NAME="Oracle Linux Server 9.4"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:oracle:linux:9:4:server"
HOME_URL="https://linux.oracle.com/"
BUG_REPORT_URL="https://github.com/oracle/oracle-linux"
ORACLE_BUGZILLA_PRODUCT="Oracle Linux 9"
ORACLE_BUGZILLA_PRODUCT_VERSION=9.4
ORACLE_SUPPORT_PRODUCT="Oracle Linux"
ORACLE_SUPPORT_PRODUCT_VERSION=9.4
Step2: Create the new file
[root@linuxhelp ~]# vim flagscript
#!/bin/bash
# Define a function to process the arguments
process_args() {
while getopts ":a:b:c:" opt; do
case $opt in
a) echo "Argument a: $OPTARG" ;;
b) echo "Argument b: $OPTARG" ;;
c) echo "Argument c: $OPTARG" ;;
\?) echo "Invalid option: -$OPTARG" ;;
esac
done
}
# Call the function and pass the arguments
process_args "$@"
Step 3: Change the permissions
[root@linuxhelp ~]# chmod +x flagscript
Step4: Run the script
[root@linuxhelp ~]# ./flagscript -a welcome
Argument a: welcome
[root@linuxhelp ~]# ./flagscript -a welcome -b boys
Argument a: welcome
Argument b: boys
[root@linuxhelp ~]# ./flagscript -a welcome -b boys -c hello
Argument a: welcome
Argument b: boys
Argument c: hello
[root@linuxhelp ~]# ./flagscript -a welcome -b boys -c hello -d hi
Argument a: welcome
Argument b: boys
Argument c: hello
Invalid option: -d
Conclusion :
We have reached the end of this article. In this guide, we have walked you through the steps required to Pass Multiple Arguments to Multiple Flags on Bash Script in Oracle Linux 9.4
Comments ( 0 )
No comments available