Three articles of passing parameters Shell

We can in the implementation of Shell script to pass parameters to the script, to obtain parameters in script format is: $ the n- . n represents a number, 1 is the first parameter to execute the script, 2 is the second parameter of the script execution, and so ......


Examples

Three parameters passed to the script, and outputs, where $ 0 for the implementation of the file name:

#!/bin/bash

echo "Shell 传递参数实例!";
echo "执行的文件名:$0";
echo "第一个参数为:$1";
echo "第二个参数为:$2";
echo "第三个参数为:$3";

Script executable permissions set, and executes the script, the output results are as follows:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
Shell 传递参数实例!
执行的文件名:./test.sh
第一个参数为:1
第二个参数为:2
第三个参数为:3


Special characters

In addition, there are several parameters to handle special characters:

Parameter Handling Explanation
$# Number of arguments passed to the script
$* Show all parameters passed to the script to a single string. Such as "$ *" with "" "enclosed in the case, the form of" $ 1 $ 2 ... $ n "output of all parameters.
$$ The script runs the current process ID number
$! Finally, a process running in the background ID number
$@ $ * The same, but the use of quotation marks, and returns each parameter in quotation marks. Such as "$ @" with "" "enclosed in the case, the form of" $ 1 "" $ 2 "..." $ n "output of all parameters.
$- Shell used to display the current option, and set command the same function.
$? Displays exit status of the last command. 0 means no error, any other value indicates an error.

Examples are as follows:

#!/bin/bash

echo "Shell 传递参数实例!";
echo "第一个参数为:$1";

echo "参数个数为:$#";
echo "传递的参数作为一个字符串显示:$*";

Executing the script, the output results are as follows:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
Shell 传递参数实例!
第一个参数为:1
参数个数为:3
传递的参数作为一个字符串显示:1 2 3


$ * And $ @ difference

  • The same point: all references to all parameters.
  • Differences: only reflected in double quotes. Suppose three parameters 1,2,3 write the script runs ,, the "*" is equivalent to "123" (a passed parameter), the "@" is equivalent to "1" "2" " 3 "(passed three parameters).
#!/bin/bash

echo "-- \$* 演示 ---"
for i in "$*"; do
    echo $i
done

echo "-- \$@ 演示 ---"
for i in "$@"; do
    echo $i
done

Executing the script, the output results are as follows:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
-- $* 演示 ---
1 2 3
-- $@ 演示 ---
1
2
3


reference:

Shell transmission parameters


Guess you like

Origin www.cnblogs.com/linuxAndMcu/p/11119470.html