Command Line arguments

Certainly! Here's an example of a shell script that demonstrates command-line arguments:

#!/bin/bash

# Accessing command-line arguments
echo "Total number of arguments: $#"
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"

In this script, we have the following command-line argument-related operations:

  • Accessing the Total Number of Arguments: We use $# to access the total number of command-line arguments passed to the script. This variable stores the count of arguments excluding the script name itself.

  • Accessing the Script Name: We use $0 to access the script name itself. This variable contains the name of the script being executed.

  • Accessing Individual Arguments: We use $1, $2, and so on to access the individual command-line arguments. $1 represents the first argument, $2 represents the second argument, and so on.

  • Accessing All Arguments: We use $@ to access all the command-line arguments as a list. This variable represents an array-like structure containing all the arguments passed to the script.

When you run the script, it will display the total number of arguments, the script name, the first argument, the second argument, and all arguments passed to the script.

For example, if you run the script as ./script.sh argument1 argument2, the output will be:

Total number of arguments: 2
Script name: ./script.sh
First argument: argument1
Second argument: argument2
All arguments: argument1 argument2

You can modify and expand this script to handle additional command-line arguments, perform validation or conditional checks on the arguments, and use them in your script's logic. Command-line arguments provide a way to pass input or configuration to shell scripts and make them more flexible and reusable.

Last updated