How to Pass Command Line Arguments in Shell Scripting

Introduction

Hello Folks :) In this article, we will be learning several ways of passing command-line arguments to BASH shell scripts. BASH shell scripts take in command-line arguments as inputs both sequentially and also, parsed as options. 

The command-line utilities use arguments to trigger functions in a Bash script or choose between environments to execute the script. In Bash, arguments are configured in different ways as per the requirements.

Positional Command Line Input Arguments

Bash Input arguments are read in a positional manner, from position $1, $2, ..$n. The pattern $ followed by an integer is a reserved structure to represent the command-line input arguments. 

"$@" expands into a list of separate parameters. 

"$*" is one parameter consisting of all the parameters added together. 

"$#" refer to the value of the total number of command line arguments passed.

$0 denotes the name of the script.

Here's a pictorial representation of positional command-line input arguments used to invoke a script:



Example - Creating a Command-Line Program

Here's a pictorial representation of positional command-line input arguments used to invoke a script. Consider the following script, demo.sh, where the arguments are printed according to their positions: 

$ vim demo.sh

#!/bin/bash
echo "Script name: $0"
echo "Input Arg 1: $1"
echo "Input Arg 2: $2"
echo "Input Arg 3: $3"
echo "-----------"
echo "All Input Args: $*"
echo "All Input Args: $@"
echo "Input Arg count: $#"

This shell script is executed with the arguments as shown below:

bash demo.sh 1 2 3 

Script name: demo.sh
Input Arg 1: 1
Input Arg 2: 2
Input Arg 3: 3
-----------
All Input Args: 1 2 3 
All Input Args: 1 2 3 
Input Arg count: 3 

Conclusion

In this article, we have covered the basics of passing the command line input arguments to a shell script. The example shows that we created the BASH script which uses the arguments that we provided to the script.


No comments:

Powered by Blogger.