How are command-line arguments accessed in bash?

In bash, command-line arguments are accessed using special variables. Here's how you can access them:

  • $0: Represents the name of the script.
  • $1: Represents the first command-line argument.
  • $2: Represents the second command-line argument.
  • $3, $4, etc.: Represent subsequent command-line arguments.
  • $@: Represents all command-line arguments as separate words.
  • $#: Represents the total number of command-line arguments passed to the script.

Example

Here’s a simple script that demonstrates how to access command-line arguments:

#!/bin/bash
echo "Script name: $0"
echo "Total arguments: $#"
echo "First argument: $1"
echo "Second argument: $2"

To run the script, use the following command:

bash script_name.sh arg1 arg2

This will output:

Script name: script_name.sh
Total arguments: 2
First argument: arg1
Second argument: arg2

This way, you can easily access and utilize command-line arguments in your bash scripts.

0 Comments

no data
Be the first to share your comment!