The best Shell passing parameters Tutorial In 2024, In this tutorial you can learn Shell passing parameters

Shell passing parameters

We can in the implementation of Shell script to pass parameters to the script, the script takes parameters within theformat: $ n.n represents a number, 1 for the first execution of the script parameter, 2 for the second parameter to execute the script, and so on /en/en/en

Examples

The following examples we pass three parameters to the script, and outputs, where $ 0 is the name of the file to execute:

#!/bin/bash
# author:本教程
# url:www.w3write.com

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

Set executable permissions to the script and execute the script, the output is as follows:

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

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

Parameter handling Explanation
$ # The number of parameters passed to the script
$ * In a single string displays all parameters passed to the script.
Such as "$ *" with "" "enclosed case, the form of" $ 1 $ 2 /en. $ n "output of all parameters.
$$ The current process ID number of the script runs
$! Finally, a process running in the background ID number
$ @ * $ With the same, but when you use quotation marks, and returns each parameter in quotes.
Such as "$ @" with "" "enclosed case, the form of" $ 1 "" $ 2 "/en." $ n "output of all parameters.
$ - Shell displays the current option to use, and set the command the same function.
$? Displays exit status of the last command. 0 indicates no errors, and any other value indicates an error.
#!/bin/bash
# author:本教程
# url:www.w3write.com

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

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

Execute the script, the output is 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 the script runs when writing the three parameters 1,2,3 ,, "*" is equivalent to "123" (pass a parameter), and "@" is equivalent to "1", "2", " 3 "(passed three parameters).
#!/bin/bash
# author:本教程
# url:www.w3write.com

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

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

Execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh 1 2 3
-- $* 演示 ---
1 2 3
-- $@ 演示 ---
1
2
3
Shell passing parameters
10/30