When executing a Shell script, parameters can be passed to the script, and the format of parameters obtained in the script is: $n. n represents a number, 1 is the first parameter to execute the script, 2 is the second parameter to execute the script...
In the following example, we pass three parameters to the script and output them separately, where $0 is the filename to be executed
# cat test.sh
#!/bin/bash
echo "Shell pass parameter example";
echo "File name: $0";
echo "First parameter: $1";
echo "Second parameter: $2";
echo "Third parameter: $3";
output result
# sh test.sh 1 2 3
Shell passing parameter example
File name: test.sh
first parameter: 1
Second parameter: 2
Third parameter: 3
The following special characters are used to process parameters:
parameter handlingillustrate
$#The number of arguments passed to the script
$*Displays all parameters passed to the script as a single string.
For example, when "$*" is enclosed in """, all parameters are output in the form of "$1 $2 ... $n".
$$The current process ID number of the script running
$!ID number of the last process running in the background
$@Same as $*, but used with quotes, returning each argument in quotes.
For example, when "$@" 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.
$?Displays the exit status of the last command. 0 means no error, any other value means there is an error.
Difference between $* and $@:
The same point: all parameters are quoted.
Difference: Only reflected in double quotes. Assuming that three parameters 1, 2, 3 are written when the script is running, " * " is equivalent to "1 2 3" (one parameter is passed), and "@" is equivalent to "1" "2" " 3" (three arguments were passed).
The following example:
# vi test.sh
#!/bin/bash
for i in "$*";do
echo $i
done
echo "------------"
for i in "$@";do
echo $i
done
output
# sh test.sh 1 2 3
1 2 3
------------
1
2
3