We can pass information to a shell program using command line arguments, the same as any other Linux command. These command line arguments can be used within the shell program. They are stored in variables, accessible within the program.
The command line arguments are stored in variables that show the position of the argument in the command line. That is why these are also called positional parameters. The variables that store command line arguments have names from $0 to $9. Beginning with the tenth command line argument, the argument number is enclosed in braces.
Variable Name | Description |
---|---|
$ 0 | Shows value of the command itself (program name) |
$ 1 | First command line argument |
$ 2 | Second command line argument |
. | . |
. | . |
. | . |
$ 9 | Ninth command line argument |
${10} | Tenth command line argument |
# $ | Total number of command line arguments |
# * | A space-separated list of command line arguments |
Let's see script, which shows how many command line arguments are provided, a list of all arguments, and the value of the first argument. This program is now shown using the cat command.
#!/usr/bin/sh
echo " Total number of command line arguments is: $# "
echo " These arguments are: $* "
echo " The first argument is: $1 "
$
When we execute the program with three arguments red, green, and blue, the result is as shown below :
$ ./script red green blue
Total number of command line arguments is: 3
These arguments are: red green blue
The first argument is: red
$