How do I parse command line arguments in Bash?

 

In Bash, you can parse command-line arguments using special variables and constructs. The most common way to do this is by using the $1, $2, $3, etc., variables to access individual command-line arguments, and by using loops and conditionals for more complex parsing. Here's a simple example:

bash
#!/bin/bash # Parse command-line arguments while [[ $# -gt 0 ]]; do case "$1" in -f|--file) file="$2" shift 2 ;; -d|--directory) directory="$2" shift 2 ;; --flag) flag=true shift ;; *) echo "Unknown option: $1" exit 1 ;; esac done # Display parsed arguments echo "File: $file" echo "Directory: $directory" echo "Flag: $flag"

In this script:

  • We use a while loop to iterate through the command-line arguments.
  • Inside the loop, we use the case statement to match and handle different options.
  • The options are specified with -f, -d, and --flag, and they are followed by their corresponding values.
  • We shift the argument list to remove the processed options and their values.
  • If an unknown option is encountered, we display an error message and exit.

Here's how you can run the script with various command-line arguments:

bash
./script.sh -f myfile.txt -d /path/to/directory --flag

This command sets the file variable to "myfile.txt," the directory variable to "/path/to/directory," and the flag variable to "true."

You can customize the script to match your specific requirements and add more options as needed. This is a basic example, and you can expand it to handle more complex argument parsing scenarios.

Comments