shell基础--shell特殊变量

一.变量列表

二.实验

系统:centos 7

1.特殊变量

[root@~_~ day2]# cat p.sh
#!/bin/bash
echo '$0:'$0
echo '$*:'$*
echo '$@:'$@
echo '$#:'$#
echo '$1$2$3:' $1$2$3
[root@~_~ day2]# sh p.sh a b c d
$0:p.sh
$*:a b c d
$@:a b c d
$#:4
$1$2$3: abc

2.$$

[root@~~ day2]# echo $$
1974

3.shift命令: 移位位置参数,重命名位置参数 $N+1、$N+2 ... 到 $1、$2 ... 如果没有给定 N,则假设为1。每次移动之后$#会少N

退出状态:
返回成功,如N 为负或者大于 $#则失败

(1).例子一,移动位置变量

[root@~_~ day3]# cat r.sh
#!/bin/bash
until [ $# -eq 0 ]
do
echo "the first value is:$1 the number of values is:$#"
shift
done
[root@~_~ day3]# sh r.sh 1 2 3 4 5
the first value is:1 the number of values is:5
the first value is:2 the number of values is:4
the first value is:3 the number of values is:3
the first value is:4 the number of values is:2
the first value is:5 the number of values is:1

(2).例子二,利用shift移位进行累加

[root@~_~ day3]# cat s.sh
#!/bin/bash
sum=0
until [ $# -eq 0 ]
do
sum=`expr $sum + $1`
shift
done
echo "sum is:$sum"
[root@~_~ day3]# sh s.sh 1 2 3 4 5
sum is:15

注意:以上的位移量都是1,位移量大于1时,输入参数个数的不同,可能会有逻辑错误。

原文地址:https://www.cnblogs.com/ajilisiwei/p/6654246.html