Skip to content

Latest commit

 

History

History
90 lines (73 loc) · 2.52 KB

File metadata and controls

90 lines (73 loc) · 2.52 KB

Command-Line Arguments

Command-line arguments provide a way to pass inputs to a shell script during its execution. This guide explores the processing of command-line arguments, including handling options and flags.

Processing Command-Line Arguments

Shell scripts can accept command-line arguments, which are provided after the script name during execution. The positional parameters $1, $2, etc., represent these arguments.

Example 1: Basic Command-Line Arguments

#!/bin/bash

# Process command-line arguments
echo "First argument: $1"
echo "Second argument: $2"
echo "Number of arguments: $#"
echo "All arguments: $@"

In this example, the script prints the first and second command-line arguments, the total number of arguments, and all arguments provided.

Example 2: Iterating Through Command-Line Arguments

#!/bin/bash

# Iterate through command-line arguments
for arg in "$@"; do
  echo "Argument: $arg"
done

Here, the script uses a for loop to iterate through all command-line arguments provided.

Options and Flags

Options and flags provide a way to modify the behavior of a script by specifying certain parameters during execution.

Example 3: Using Getopts for Options

#!/bin/bash

# Process options using getopts
while getopts ":a:b:" opt; do
  case $opt in
    a)
      echo "Option 'a' with value: $OPTARG"
      ;;
    b)
      echo "Option 'b' with value: $OPTARG"
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      ;;
  esac
done

In this example, the script uses getopts to process options (-a and -b) and their corresponding values.

Example 4: Handling Flags

#!/bin/bash

# Process flags
verbose=false
debug=false

while [ $# -gt 0 ]; do
  case "$1" in
    -v|--verbose)
      verbose=true
      ;;
    -d|--debug)
      debug=true
      ;;
    *)
      echo "Invalid argument: $1"
      exit 1
      ;;
  esac
  shift
done

echo "Verbose mode: $verbose"
echo "Debug mode: $debug"

Here, the script processes flags (-v or --verbose and -d or --debug) to enable or disable certain features.

Key Takeaways

  • Processing Command-Line Arguments: Use special variables like $1, $2, etc., and $@ to access command-line arguments.
  • Options and Flags: Utilize tools like getopts for handling options with values, and use conditional checks for processing flags.

These examples showcase how to effectively process command-line arguments, options, and flags in shell scripting. Experiment with different combinations to meet your script's requirements.