Exploring Bash — Part 6

Dineshkumaar R
5 min readApr 11, 2024

--

Introduction

Hey Friends, Welcome back to my Bash exploration blog series! Let’s dive right in! Today, we’ll be delving into the intricacies of command-line arguments, positional parameters, parsing techniques, flags and options handling, as well as the usage of ‘getopts’ for streamlined option parsing.

Command-Line Arguments

Command-line arguments are inputs provided to a script or program when it is executed. They enable users to customize the behavior of the script without modifying its code. Understanding how to work with command-line arguments is crucial for creating flexible and user-friendly Bash scripts.

Accessing Arguments

In Bash scripts, command-line arguments are accessed using special variables. ‘$1', ‘$2', etc., represent individual arguments, while ‘$@’ represents all arguments as a single string and ‘$*’ represents all arguments as separate strings.

#!/bin/bash

echo "First argument: $1" # Prints the first argument passed to the script
echo "All arguments: $@" # Prints all arguments passed to the script

Positional Parameters

Positional parameters correspond to command-line arguments passed to a script. They allow you to reference specific arguments by their position using variables like ‘$1', ‘$2', etc.

#!/bin/bash

echo "Script name: $0" # Prints the name of the script itself
echo "First argument: $1" # Prints the first positional parameter
echo "Second argument: $2" # Prints the second positional parameter

Parsing Arguments

Parsing command-line arguments involves iterating over and processing the arguments passed to a script. This can be done using loops and conditional statements to handle different cases and validate inputs.

#!/bin/bash

for arg in "$@"
do
if [ "$arg" == "-h" ] || [ "$arg" == "--help" ]
then
echo "Usage: script_name [options]"
exit 0
fi
done

Flags and Options

Flag: A flag is a small piece of information used to modify the behavior of a command or script. It’s often represented by a single character preceded by a hyphen (e.g., -v) or by a word preceded by two hyphens (e.g., --verbose). Flags typically don’t take additional arguments; they’re just used to enable or disable certain features.

Option: An option is a command-line parameter used to provide additional information or settings to a command or script. Options are usually followed by a value, which can be specified directly after the option name or separated by a space. Options are commonly represented by a single character preceded by a hyphen (e.g., -o filename) or by a word preceded by two hyphens (e.g., --output filename).

Example:

#!/bin/bash

# Initialize variables for flag and option
verbose=false
name=""

# Parse command-line arguments
while [[ "$#" -gt 0 ]]; do
case "$1" in
-v|--verbose)
verbose=true
echo "Verbose mode enabled"
;;
-n|--name)
name="$2"
shift
echo "Name set to: $name"
;;
*)
echo "Unknown option: $1"
exit 1
;;
esac
shift
done

• Variables initialized for flag and option processing.
• Script iterates through command-line arguments.
• Sets ‘verbose’ to true and prints message if ‘-v’ or ‘ --verbose’ encountered.
• Sets ‘name’ to next argument’s value and prints message if ‘-n’ or ‘ --name’ encountered.
• Prints error message and exits if unknown option encountered.
• Shifts to the next argument after processing each one.

Using getopts

The ‘getopts’ built-in command simplifies the parsing of command-line options by providing a convenient way to handle flags and options in Bash scripts.

• getopts is a built-in command in Bash.
• It simplifies parsing of command-line options.
• Syntax: getopts optstring name [args].
• optstring specifies expected options, colon (:) denotes option with argument.
• name is the variable storing current option.
• Typically used in a while loop to iterate over options.
• Each option is processed in a case statement.
• OPTARG stores argument for options requiring one.
• Handles error checking, detecting invalid options.
• Sets ? for invalid options, stores in OPTARG.
• Provides automatic argument shifting.
• Offers standardized and efficient option handling in Bash scripts.

#!/bin/bash

while getopts ":f:o:" opt
do
case $opt in
f)
flag=true
;;
o)
option="$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done

• The script initiates a while loop using getopts to parse command-line options.
• Options specified are -f (flag) and -o (option), where -o requires an argument.
• Inside the loop, a case statement handles each option encountered.
• If -f is found, it sets the variable flag to true.
• If -o is found, it sets the variable option to the value of its argument.
• An \? case catches invalid options and prints an error message to standard error.
• After processing all options, the loop exits, and the script continues.

Handling Arguments with Spaces

To handle arguments that contain spaces or special characters, proper quoting and escaping techniques must be employed to ensure correct processing.

#!/bin/bash

# Script with double quotes
echo "First argument with spaces (with double quotes): \"$1\""

# Script without double quotes
echo "First argument with spaces (without double quotes): $1"

Summary of the blog

1. Command-line arguments: Enable customization, accessed via variables.
2. Positional parameters: Correspond to arguments, accessed by position.
3. Parsing: Involves iterating, validating, and handling cases.
4. Flags and options: Modify behavior, flags enable/disable, options provide settings.
5. Handling: Initialization, parsing, processing, ensure proper quoting and escaping.
6. getopts: Simplifies option parsing, handles error checking, automatic shifting.

URL’s :

  1. Exploring bash — Part1 : https://medium.com/@dineshkumaar478/exploring-bash-part-1-3dabf4b5ef9e
  2. Exploring bash — Part2 : https://medium.com/@dineshkumaar478/exploring-bash-part-2-71f341fb5700
  3. Exploring bash — Part3 : https://medium.com/@dineshkumaar478/exploring-bash-part-3-db1fc958eb17
  4. Exploring bash — Part4 :https://medium.com/@dineshkumaar478/exploring-bash-part-4-4521aaac30ea
  5. Exploring bash — Part5 : https://medium.com/@dineshkumaar478/exploring-bash-part-5-a136eb036b4f

Thank you for taking the time to read my blog. Wishing you a joyful learning experience ahead!

--

--

Dineshkumaar R

🔐 Cyber Security Engineer | Penetration Tester | VAPT Specialist | 🚩 Hackthebox (Pro Hacker) | 🏆 Tryhackme (Guru)