Command Line Arguments in Shell Script
Command line arguments are also known as positional parameters. These arguments are specific with the shell script on terminal during the run time. Each variable passed to a shell script at command line are stored in corresponding shell variables including the shell script name.
Synatx:
./myscript.sh ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10
See the below image to understand the command line values and variables. Here ARG1, ARG2 to ARG10 are command line values, which is assigned to corresponding shell variables.
These are also known as special variables provided by the shell. Except above screenshot, there are some more special variables as given below.
Example Script
Command line arguments can be passed just after script file name with space separated. If any argument have space, put them under single or double quote. Read below simple script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/bin/bash ### Print total arguments and their values echo "Total Arguments:" $# echo "All Arguments values:" $@ ### Command arguments can be accessed as echo "First->" $1 echo "Second->" $2 # You can also access all arguments in an array and use them in a script. args=("$@") echo "First->" ${args[0]} echo "Second->" ${args[1]} |
Now execute this script with 2 arguments and found following results.
$ ./arguments.sh Hello TecAdmin