1、位置参数变量
位置参数变量 | 作用 |
$n | n为数字,$0代表命令本身,$1-$9代表第一到第九个参数,十以上的参数需要用大括号包含,如${10} |
$* | 这个变量代表命令行中所有的参数,$*把所有的参数看成一个整体 |
$@ | 这个变量也代表命令行中所有的参数,不过$@把每个参数区分对待 |
$# | 这个变量代表命令行中所有参数的个数 |
》$n 一般用于获取比如用户输入的内容,通过该变量向系统传递用户所输入的内容。
[root@localhost ~]#cd sh
[root@localhost sh]#vim canshu1.sh
#!/bin/bash
echo $0
echo $1
echo $2
echo $3
~
~
[root@localhost sh]#
[root@localhost sh]#chmod 755 canshu1.sh
[root@localhost sh]#./canshu1.sh
./canshu1.sh
[root@localhost sh]#./canshu1.sh 11 22 33 44 55
./canshu1.sh
11
22
33
[root@localhost sh]#
示例2:简单的加法计算器(当前有很多漏洞)
[root@localhost sh]#vim jiafajisuanqi.sh
#!/bin/bash
num1=$1
num2=$2
sum=$(($num1 + $num2))
#变量sum的和是num1+num2
echo $sum
#打印变量sum的值
~
~
[root@localhost sh]#chmod 755 jiafajisuanqi.sh
[root@localhost sh]#./jiafajisuanqi.sh 2 3
5
》示例三
[root@localhost sh]#vim shili3.sh
#!/bin/bash
echo "A total of $# parameters"
#使用$#代表所有参数的个数
echo "The parameters is:$*"
#使用$*代表所有的参数
echo "The parameters is:$@"
#使用$@也代表所有参数
[root@localhost sh]#chmod 755 shili3.sh
[root@localhost sh]#./shili3.sh
A total of
The parameters is:
The parameters is:
[root@localhost sh]#./
canshu1.sh hello.sh jiafajisuanqi.sh shili3.sh
[root@localhost sh]#./shili3.sh 4 55 44 3 2 5
A total of 6 parameters
The parameters is:4 55 44 3 2 5
The parameters is:4 55 44 3 2 5
[root@localhost sh]#
示例4、$*与$@的区别
[root@localhost sh]#vim canshu4.sh
#!/bin/bash
for i in "$*"
#$* 中所有参数看成是一个整体,所以这个for循环只会循环一次
do
echo "The parameters is:$i"
done
x=1
for y in "$@"
#$@中的每个参数都看成是独立的,所以“$@"中,有几个参数就会循环几次
do
echo "The parameter $x is:$y"
x=$(( $x + 1 ))
done
~
[root@localhost sh]#
[root@localhost sh]#chmod 755 canshu4.sh
[root@localhost sh]#./canshu
canshu1.sh canshu4.sh
[root@localhost sh]#./canshu4
bash: ./canshu4: 没有那个文件或目录
[root@localhost sh]#./canshu4.sh 3 4 3 2
The parameters is:3 4 3 2
The parameter 1 is:3
The parameter 2 is:4
The parameter 3 is:3
The parameter 4 is:2
[root@localhost sh]#