table of Contents
(2) Processing parameter special characters
(1)$n passes parameters
When executing a Shell script, pass parameters to the script, and the format for obtaining parameters in the script is: $n.
n represents a number, 1 is the first parameter of the execution script, 2 is the second parameter of the execution script, and so on.
In the following example, we pass three parameters to the script and output them separately, where $0 is the name of the file to be executed:
Set executable permissions for the script and execute the script, the output result is as follows:
$ chmod +x test.sh
$ ./test.sh 1 2 3
Shell 传递参数实例!
执行的文件名:./test.sh
第一个参数为:1
第二个参数为:2
第三个参数为:3
(2) Processing parameter special characters
Parameter handling |
Description |
$# |
Number of parameters passed to the script |
$* |
Display all the parameters passed to the script in a single string. If "$*" is enclosed in """, all parameters are output in the form of "$1 $2… $n". |
$$ |
ID number of the current process running the script |
$! |
ID number of the last process running in the background |
$@ |
Same as $*, but use quotation marks and return each parameter in quotation marks. If "$@" is enclosed in """, all parameters are output in the form of "$1" "$2"… "$n". |
$- |
Displays the current options used by the Shell, which has the same function as the set command. |
$? |
Display the exit status of the last command. 0 means there is no error, any other value means there is an error. |
#!/bin/bash
#author:Novice Tutorial
# url: www.runoob.com
echo "Shell passes parameter examples!";
echo "The first parameter is: $1";
echo "The number of parameters is: $#";
echo "The passed parameter is displayed as a string: $*";
Execute the script and the output result is as follows:
$ chmod +x test.sh
$ ./test.sh 1 2 3
Shell passing parameter example!
The first parameter is: 1
The number of parameters is: 3
The passed parameter is displayed as a string: 1 2 3