In Shell scripts, command-line arguments are values passed to the script when it is executed. These parameters enhance the script's flexibility and dynamism, enabling it to perform different actions based on the input.
Command-line arguments are typically accessed within the script using special variables, which include:
$0- This denotes the script's name.$1to$9- These represent the first through ninth command-line arguments.$#- This indicates the total number of arguments passed to the script.$@or$*- These represent all command-line arguments.
For example, if you have a script named script.sh and you want to handle two input parameters, you can call the script as follows:
bash./script.sh param1 param2
Within the script, you can access param1 and param2 using $1 and $2. Here is a simple example script:
bash#!/bin/bash # script.sh echo "Script name: $0" echo "First parameter: $1" echo "Second parameter: $2" echo "Total number of parameters: $#"
When executing ./script.sh Apple Banana, the output will be:
shellScript name: ./script.sh First parameter: Apple Second parameter: Banana Total number of parameters: 2
By utilizing command-line arguments, Shell scripts can execute different tasks based on input, thereby making the scripts more versatile and useful.