Command Line Arguments in Shell Script

Command Line Arguments in Shell Script

 Command Line Arguments in Shell Script


Command-line arguments are also known as positional parameters. These arguments are specific to the shell script on the terminal during the run time. Each variable passed to a shell script at the command line is stored in corresponding shell variables including the shell script name.

Syntax:

./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 are 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.

 Special Variable
 Variable Details
 $1 to $n
$1 is the first argument, $2 is the second argument till $n n’th arguments. From 10’th argument, you must need to enclose them in braces like ${10}, ${11} and so on
 $0
The name of the script itself
 $$
Process id of the current shell
 $*
Values of all the arguments. All arguments are double-quoted
 $#
Total number of arguments passed to script
 $@
Values of all the arguments
 $?
Exit status id of the last command
 $!
Process id of the last command

Example Script

Command-line arguments can be passed just after the script file name with space-separated. If any arguments have space, put them under single or double quotes. Read the below simple script.

Now execute this script with 2 arguments and find the following results.

$ ./arguments.sh Hello Test
Reactions

Post a Comment

0 Comments

close