shell 基础2

位置参数变量:
$n: $0代表命令本身,$1-$9代表第一到第九个参数,十以上的参数需要用大括号包含,如${10}
$*: 这个变量代表命令行中所有的参数,$*把所有的参数看成一个整体
$@: 这个变量也代表命令行中所有的参数,不过$*把每个参数区分对待
$#: 这个变量代表命令行中所有参数的个数,不算命令本身

例子:
vim 2.sh

#!/bin/bash
echo $0
echo $1
echo $2
echo $3
echo $4
[root@localhost tmp]# ./2.sh 0 1 2 3
./2.sh
0
1
2
3

分析:$0 代表本条命令本身 $1 接收第一个参数,$2接收第二个参数。。。

例子:
[root@localhost tmp]# cat 3.sh
#!/bin/bash
sum=$(($1+$2))
echo "sum is $sum"

./3.sh 3 4
输出:sum is 7

例子:
#!/bin/bash
for i in "$*"
do
echo "The param is :$i"
done

x=1
for y in "$@"
do
echo "The param$x is: $y"
x=$(($x+1))
done

执行结果:
[root@localhost tmp]# ./3.sh 1 2 3 4 5 6 7 8
The param is :1 2 3 4 5 6 7 8
The param1 is: 1
The param2 is: 2
The param3 is: 3
The param4 is: 4
The param5 is: 5
The param6 is: 6
The param7 is: 7
The param8 is: 8

$*:所有参数作为一个整体
$@:每个参数都是单独的

原文地址:https://www.cnblogs.com/javasl/p/11155127.html