Reading With Parameter Names
Using getopts to parse arguments and parameters
We can use the getopts program/ command to parse the arguments passed to the script in the command line/ terminal by using loops and switch-case statements.
#!/bin/bash while getopts n:c: option do case "${option}" in n)nation=${OPTARG};; c)code=${OPTARG};; esac done echo "Nation : $nation" echo "code : $code"
Using getopts, we can assign the positional arguments/ parameters from the command line to the bash variables directly. This allows us to manage the parameters nicely and in a systematic way. In the above script, we have used two arguments to store the bash variables using the getopts syntax, while loops and switch-case statements.
Printing Values of All Arguments
We can print the arguments passed to the script by a simple powerful variable ‘@’ which stores all the parameters passed.
#!/bin/bash echo "The arguments passed in are : $@"
Accessing the number of Parameters passed
We can also use the variable ‘#’ to access the number of parameters passed from the command line. The # variable basically contains the number of parameters/ arguments which are passed into the script.
#!/bin/bash echo "The number of arguments passed in are : $#"
The following were the process and specification of passing and parsing the variables in the bash script. The logic of shifting and making modifications to the variables is in the hands of the user. This was just a demonstration of passing in and parsing down the arguments from the command line to the script to make them more dynamic.
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.
Contact Us