Friday, May 17, 2013

Shell script $# $@ $- $$

Command Line Arguments


Command line arguments are treated as special variables within the script, the reason I am calling them variables is because they can be changed with the shift command. The command line arguments are enumerated in the following manner $0, $1, $2, $3, $4, $5, $6, $7, $8 and $9. $0 is special in that it corresponds to the name of the script itself. $1 is the first argument, $2 is the second argument and so on. To reference after the ninth argument you must enclose the number in brackets like this ${nn}. You can use the shift command to shift the arguments 1 variable to the left so that $2 becomes $1, $1 becomes $0 and so on, $0 gets scrapped because it has nowhere to go, this can be useful to process all the arguments using a loop, using one variable to reference the first argument and shifting until you have exhausted the arguments list.



As well as the commandline arguments there are some special builtin variables:



•$# represents the parameter count. Useful for controlling loop constructs that need to process each parameter.



•$@ expands to all the parameters separated by spaces. Useful for passing all the parameters to some other function or program.



•$- expands to the flags(options) the shell was invoked with. Useful for controlling program flow based on the flags set.



•$$ expands to the process id of the shell innovated to run the script. Useful for creating unique temporary filenames relative to this instantiation of the script.



Note

The commandline arguments will be referred to as parameters from now on, this is because SH also allows the definition of functions which can take parameters and when called the $n family will be redefined, hence these variables are always parameters, its just that in the case of the parent script the parameters are passed via the command line. One exception is $0 which is always set to the name of the parent script regardless of whether it is inside a function or not.





No comments:

Post a Comment