How To Pass and Parse Linux Bash Script Arguments and Parameters
Bash is powerful scripting language provides by various Linux distributions,Unix and BSD. If we need to make our script dynamic we generally use arguments. Arguments are provided to the script through command line. In this tutorial we will examine different use cases of argument passing and examples.
In order to use externally provided values inside bash script we should provide them after the script name. Following syntax assumes the script is executable.
myscript.sh PARAM1 PARAM2 ...
Or we can use
bash in order to interpret our script like below and provide parameters.
bash myscript.sh PARAM1 PARAM2 ...
We have learned the syntax of the arguments. In this example we will look use cases about argument passing. We will provide two arguments for example.
$ myscript.sh 1 3
If we need provide string with multiple words we can use single or double quotes. In this example we will prove
Hello Poftut as two separate argument.
$ myscript.sh 10 "Hello Poftut"
Read Argument Inside Script
Now the real work starts now. We have learned how to provide arguments from shell or command line. In this part we will look how to read them inside script. Bash provides
$2 , … like usage for reading input arguments inside script. the first argument can be accessed from variable name
$1 , second one
$2 and so …
In this example we will provide two argument
Poftut to script.
echo $1 $2
As we can see provided arguments are printed with
Assign Provided Arguments To Bash Variable
Another use case for bash variables is assigning them new variables with meaningful names. This will give us ability to change provided values and use them properly with their names. In this example we will put
Poftut into variables named
echo $salute $name
Read Multiple Arguments with For or While
Some times some arguments will not fit our condition and we may need a lot of argument to provide and use them in a iterative way. In this condition we can use bash loop mechanisms
while . We can iterate over given arguments like and array or list with
while . In this example we will iterate over provided arguments and print them to the shell. We will use
$@ to specify the list of provided arguments and put each item into variable named
var in each step.
for var in "$@"
Read With Parameter Names
As regular Linux applications we can use parameter names for arguments and parse them accordingly. We will use
getops function which will parse provided options in an array. In this example we will use
while loop with
case structure. We will parse the provided parameter names
u which is username and
while getopts u:p: option