Some notes about passing parameters and arguements to a bash script.
we can pass parameters to bash scripts. Inside a function or script we use the following variables for the parameters:
$0: the name of the script to be used
$1: the first parameter
$*: a collection of all the parameters separated according to IFS (internal field separator)
(The default IFS value is a blank, tab, and newline. )
"$*": a collection of all parameters in the form of one word
$@ : a collection of all parameters with each separated by IFS
"$@": a collection fo all parameters separated, with blank space ignore
$#: number of parameters passed to the script
$?: The return code of the previous command
$$: The PID of the shell which execute the script
$!: The PID of the previous process launched in the background
When we pass aguements to a script/function in linux, we can use getopt.
for example:
echo "OPTIND starts at $OPTIND"
The OPTIND variable is initially set to 1. Thereafter it contains the index of the next parameter to be processed.
getopts ":pq:" optname:
The getopts command returns true if an option is found. The first argument to getopts is a list of option letters to be recognized, in this case, p and r. The first colon : in this example tells getopts to be silent and suppress the normal error messages, as this script will provide its own error handling. The second colon (:) after an option letter indicates that the option requires a value; for example, a -f option might be used to indicate a file name, as in the tar command.
optname is the name of a variable which will receive the name of the option found. If an option is expected to have a value, the value, if present, will be placed in the variable OPTARG.
A useful link about this question: http://www.ibm.com/developerworks/library/l-bash-parameters.html?ca=drs-
Aucun commentaire:
Enregistrer un commentaire