An example of passing parameters in Shell programming and an example of shell Parameters
When executing a Shell script, we can pass parameters to the script. The parameter format obtained in the script is $ n. N indicates a number. 1 indicates the first parameter for executing the script, 2 indicates the second parameter for executing the script, and so on ......
Instance
We pass three parameters to the script and output them separately. $0 indicates the name of the executed file:
#! /bin/bashecho "Shell pass parameters"echo "filename : $0"echo "first : $1"echo "second : $2"echo "third : $3"
Set the executable permission for the script and execute the script. The result is as follows:
In addition, there are several special characters used to process parameters:
Parameters |
Description |
$ # |
Number of scripts passed |
$ * |
Display All parameters passed to the script with a single string. For example, when "$ *" is included in... $ N "output all parameters |
$ |
ID of the current process that the script runs |
$! |
ID of the last process running in the background |
$ @ |
It is the same as $ *, but it is enclosed in quotation marks and each parameter is returned in quotation marks. For example, when $ @ is included in "", the format is "$1" "$2 "... All parameters are output in the form of "$ n. |
$- |
Displays the current options used by Shell, which have the same function as the set command. |
$? |
Displays the exit status of the last command. 0 indicates no error, and any other value indicates an error. |
$ * Similarities and differences with $:
Similarities: All parameters are referenced. Difference: It is only reflected in double quotation marks. Assume that three parameters 1, 2, and 3 are written during script execution, * is equivalent to "1 2 3" (passing a parameter ), @ is equivalent to "1", "2", and "3" (three parameters are passed ).
#! /Bin/bashecho "shell pass arguments"; echo "--- \ $ * demonstrate" for I in "$ *"; do echo $ idoneecho "--- \\ @ Demo" for I in "$ @"; do echo $ idone
The result is as follows: