0
0
Bash Scriptingscripting~30 mins

Option parsing with getopts in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Option parsing with getopts
📖 Scenario: You are writing a simple command-line tool that accepts options to customize its behavior. This tool will accept a name and an age as options and then display a greeting message.
🎯 Goal: Build a bash script that uses getopts to parse -n for name and -a for age options, then prints a greeting message using the provided values.
📋 What You'll Learn
Create variables to hold name and age
Use getopts to parse -n and -a options
Assign the option values to the correct variables
Print a greeting message using the parsed name and age
💡 Why This Matters
🌍 Real World
Many command-line tools use option parsing to customize their behavior. Learning <code>getopts</code> helps you build flexible scripts.
💼 Career
Understanding option parsing is essential for scripting tasks in system administration, DevOps, and automation roles.
Progress0 / 4 steps
1
Create variables for name and age
Create two variables called name and age and set both to empty strings.
Bash Scripting
Need a hint?

Use name="" and age="" to create empty string variables.

2
Set up getopts to parse options
Add a while loop using getopts to parse options -n and -a. Use opt as the option variable.
Bash Scripting
Need a hint?

Use while getopts "n:a:" opt; do and a case statement to assign $OPTARG to name or age.

3
Assign option values inside the loop
Inside the case statement, assign the value of $OPTARG to the variables name for option -n and age for option -a.
Bash Scripting
Need a hint?

Use n) name="$OPTARG" ;; and a) age="$OPTARG" ;; inside the case statement.

4
Print the greeting message
After the getopts loop, print the message Hello, NAME! You are AGE years old. replacing NAME and AGE with the variables name and age using echo.
Bash Scripting
Need a hint?

Use echo "Hello, $name! You are $age years old." to print the message.