Any shell script you run has access to (inherits) the environment variables accessible to its parent shell. in addition, any arguments you type after the Script Name on the shell command line are passed to the script as a series of variables.
The following parameters are recognized:
$ *
Returns a single string (''$1,$2...$ N'') Comprising all of the positional parameters separated by the internal field separator character (defined byIFSEnvironment variable ).
[Email protected]
Returns a sequence of strings (''$1'',''$2'',...''$ N'') Wherein each positional parameter remains separate from the others.
$1,$2...$N
Refers to a numbered argument to the script, whereNIs the position of the argument on the command line. In the Korn shell you can refer directly to arguments whereNIs greater than 9 Using braces. For example, to refer to the 57th positional parameter, use the notation$ {57}. In the other shells, to refer to parameters with numbers greater than 9, useShiftCommand; this shifts the parameter list to the left.$1Is lost, while$2Becomes$1,$3Becomes$2, And so on. The Inaccessible tenth parameter becomes$9And can then be referred.
$0
Refers to the name of the script itself.
$ #
Refers to the number of arguments specified on a command line.
For example, create the following shell script calledMytest:
echo There are $# arguments to $0: $* echo first argument: $1 echo second argument: $2 echo third argument: $3 echo here they are again: [email protected]
When the file is executed, you will see something like the following:
$ mytest foo bar quux There are 3 arguments to mytest: foo bar quux first argument: foo second argument: bar third argument: quux here they are again: foo bar quux
$ #Is expanded to the number of arguments to the script, while$ *And[Email protected]Contain the entire argument list. Individual parameters are accessed$0, Which contains the name of the script, and variables$1To$3Which contain the arguments to the script (from left to right along the command line ).
Although the output from[Email protected]And$ *Appears to be the same, it may be handled differently,[Email protected]Lists the positional parameters separately rather than concatenating them into a single string. Add the following to the endMytest:
function how_many { print "$# arguments were supplied." } how_many "$*" how_many "[email protected]"
The following appears when you runMytest:
$ mytest foo bar quux There are 3 arguments to mytest: foo bar quux first argument: foo second argument: bar third argument: quux here they are again: foo bar quux 1 arguments were supplied. 3 arguments were supplied.
Passing arguments to a shell script