How does bash interpret script arguments?

0119

In Bash, script arguments are interpreted using special variables that represent the command-line inputs provided when the script is executed. Here's how Bash handles these arguments:

  1. Positional Parameters:

    • $0: Represents the name of the script itself.
    • $1, $2, $3, etc.: Represent the first, second, third, and subsequent arguments passed to the script. For example, if you run ./script.sh arg1 arg2, then:
      • $0 will be ./script.sh
      • $1 will be arg1
      • $2 will be arg2
  2. Total Number of Arguments:

    • $#: This variable holds the total number of positional parameters (arguments) passed to the script. For example, if three arguments are provided, $# will be 3.
  3. All Arguments:

    • $@: This variable represents all the arguments passed to the script as separate words. It is useful for iterating over all arguments.
    • $*: Similar to $@, but treats all arguments as a single word. The difference becomes apparent when quoted.
  4. Looping Through Arguments: You can loop through all the arguments using a for loop:

    for arg in "$@"; do
        echo "Argument: $arg"
    done
    
  5. Quoting: If an argument contains spaces, it should be enclosed in quotes when passed to the script. For example:

    ./script.sh "arg with spaces"
    

Bash interprets these arguments at runtime, allowing scripts to be dynamic and flexible based on user input.

0 Comments

no data
Be the first to share your comment!