Assign Provided Arguments To Bash Variable
We can also assign it to other custom variables to make the script more dynamic and mold it according to the needs. Though the above script when run will only print two parameters, surely you can access more parameters using the variable as the order of parameters in numbers. The script can access the positional variables from the command line and use them in the required places wherever needed within the script.
#!/bin/bash a=$1 b=$2 p=$(($a*$b)) echo "The product of $a and $b = $p"
The above script accesses the positional parameters i.e $1 and $2 passed into the script and stores the user-defined variables to access them later and modify them accordingly. We can also access more parameters using iterative methods as we’ll see in the upcoming sections.
We also have the ability to check for any NULL or empty parameters passed using the -z or -n flags. From this, we can verify whether the parameters were passed or not.
#!/bin/bash if [[ -z $1 ]]; then echo "No parameter passed." else echo "Parameter passed = $1" fi
With this script, we can detect whether any positional parameters were passed in or nothing was passed. The -z flag checks for any NULL or uninitialized variables in BASH. The -z flag returns true if the variable passed is NULL or uninitialized. Hence, we can make use of basic If-else statements to detect the parameters passed.
We can also use -n flag which returns true if no parameters are passed, so we have to make use of ! to reverse the condition.
Such as follows:
#!/bin/bash if [[ ! -n $1 ]]; then echo "No parameter passed." else echo "Parameter passed = $1" fi
This script will also give the same output as well, but we are making use of -n flag instead of -z.
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