How to parse command line arguments in Bash?

Parse command line arguments in Bash

In Bash, you can use the special variables $1, $2, etc., to access command-line arguments passed to a script or function. These variables refer to the first, second, etc. argument passed to the script or function.

Here's an example script that uses command-line arguments:

#!/bin/bash

echo "The name of the script is $0"

echo "The first argument is $1"
echo "The second argument is $2"

echo "All the arguments are $@"

In this example, $0 refers to the name of the script, while $1 and $2 refer to the first and second arguments, respectively. The special variable $@ refers to all the arguments passed to the script.

To run this script and pass in some arguments, you can use the following command:

$ ./script.sh arg1 arg2

This would output the following:

The name of the script is ./script.sh
The first argument is arg1
The second argument is arg2
All the arguments are arg1 arg2

In addition to accessing individual command-line arguments, you can also use the getopts command to parse command-line options and arguments. This is a more advanced technique, but it can be useful for scripts that accept many options and arguments. The getopts command is beyond the scope of this answer, but you can refer to the Bash documentation for more information.

  1. Dynamic variable names in Bash
  2. Bash and shell script variable capitalization?
  3. How to get the directory where a Bash script is located from within the script itself?
  4. Parsing JSON with Unix tools
  5. Command not found error in Bash variable assignment
  6. How to set a variable to the output of a command in Bash?
  7. How to run Bash commands in Python?
  8. Extract filename and extension in Bash?
  9. Looping through the content of a file in Bash