Detecting Command Line Arguments
Now, we’ll see how we access those parameters inside of the script. We’ll use the number of the parameters passed in the order i.e for the first parameters passed, we’ll parse(access) the parameter by using $1 as the variable. The first parameter is stored in the $1 variable. Furthermore, you can assign this variable to any other user-defined variable you like. For the nth parameter passed, you can use $n to access that particular parameter. Here, the variable name starts with 1 because the filename/ script name is the 0th parameter. If you have more than 9 parameters, make sure to use { } around the number as without the parenthesis, bash will only see $10 as $1 and exclude the 0, so use ${10} and so on instead of simply $10.
#!/bin/bash echo "1st parameter = $1 " echo "2nd Parameter = $2 "
The above script can access the parameters from the command line/ shell using the positional parameters, which are 1, 2, 3, and so on.
As you can see, we have used {} to access the parameter variable numbers from 10 onwards. The script can be used for loops and while loops to iterate over the parameters, but we will discuss it in further sections.
How To Pass and Parse Linux Bash Script Arguments and Parameters
Parsing and Passing of Arguments into bash scripts/ shell scripts is quite similar to the way in which we pass arguments to the functions inside Bash scripts. We’ll see the actual process of passing on the arguments to a script and also look at the way to access those arguments inside the script.