Positional Parameters
Command-line arguments are passed in the positional way i.e. in the same way how they are given in the program execution. Let us see with an example.
Create a shell program that can display the command line arguments in a positional way. “Nano” editor is used to create the shell program”
The program can be executed by using the “sh” command.
sh <script filename> arg1 arg2 arg3 ......
So, our code of execution will become
sh displayPositionalArgument.sh Welcome To w3wiki
Diagrammatic representation of the above code:
Always the first argument starts after the <script filename>. <script filename> will be in the 0th location, We need to take positional arguments after the <script filename>. Hence in the above example
$1-> "Welcome" $2-> "To" $3-> "GeeksForFeeks"
Note: We can pass n number of arguments and they are identified by means of their position.
The output of the above code :
Some special variables are also to be noted while handling command-line arguments.
Special Variable | Special Variable’s details |
---|---|
$1 … $n | Positional argument indicating from 1 .. n. If the argument is like 10, 11 onwards, it has to be indicated as ${10},${11 |
$0 | This is not taken into the argument list as this indicates the “name” of the shell program. In the above example, $0 is “displayPositionalArgument.sh” |
$@ | Values of the arguments that are passed in the program. This will be much helpful if we are not sure about the number of arguments that got passed. |
$# | Total number of arguments and it is a good approach for loop concepts. |
$* | In order to get all the arguments as double-quoted, we can follow this way |
$$ | To know about the process id of the current shell |
$? and $! | Exit status id and Process id of the last command |
Bash Script – How to use Command Line Arguments
In this article, let us see about Command Line Arguments usage in Bash script. Arguments are inputs that are necessary to process the flow. Instead of getting input from a shell program or assigning it to the program, the arguments are passed in the execution part.