0
0
Bash Scriptingscripting~30 mins

Long option parsing in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Long Option Parsing in Bash Script
📖 Scenario: You are creating a simple bash script that accepts long options from the command line. This is common when you want your script to be user-friendly and clear, like many Linux commands.Imagine you want to make a script that accepts options like --name and --age to greet a user with their name and age.
🎯 Goal: Build a bash script that parses two long options --name and --age from the command line and prints a greeting message using those values.
📋 What You'll Learn
Create variables to hold the name and age
Use a while loop with a case statement to parse --name and --age options
Assign the values passed to these options to the variables
Print a greeting message using the parsed values
💡 Why This Matters
🌍 Real World
Parsing command line options is essential for making scripts user-friendly and flexible, just like many Linux commands you use daily.
💼 Career
Understanding how to parse options in bash scripts is a key skill for system administrators, DevOps engineers, and anyone automating tasks on Linux servers.
Progress0 / 4 steps
1
Create variables to hold 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 a while loop to parse command line arguments
Add a while loop that runs while [[ $# -gt 0 ]] to process all command line arguments. Inside the loop, use a case statement on $1 to check for --name and --age options.
Bash Scripting
Need a hint?

Use while [[ $# -gt 0 ]] and case "$1" in to check options.

3
Assign values to name and age inside the case
Inside the case statement, for --name assign the next argument $2 to name and shift twice. For --age, assign $2 to age and shift twice.
Bash Scripting
Need a hint?

Use name="$2" and shift 2 to assign and move to next arguments.

4
Print the greeting message using parsed name and age
Add a echo statement after the loop to print: Hello, NAME! You are AGE years old. replacing NAME and AGE with the variables name and age.
Bash Scripting
Need a hint?

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