linux 中 shift命令

 

linux 中shift命令应用与函数内部,调用一次,表示参数左移一位;$#表示shell参数的个数,调用shift一次, $#减少1.

分别处理每个参数,移出去的参数不再可用;

举例:

001、example 1

[root@pc1 test2]# ls
a.sh
[root@pc1 test2]# cat a.sh                ## 测试脚本
#!/bin/bash

echo "parameters: $*"                     ## $*是shell脚本内置变量,输出所有的参数
echo "num: $#"                            ## $#是shell内置变量,表示参数的个数
shift                                     ## 次数执行一次shift,参数左移一位
echo "shift one time: parameters: $*"     ## 输出所有参数
echo "shift one time: num: $#"            ## 输出此时的参数个数

[root@pc1 test2]# bash a.sh 10 20 30 40     ## 执行脚本,随机给与4个参数
parameters: 10 20 30 40
num: 4
shift one time: parameters: 20 30 40        ## 执行一次shift后,参数10消失,说明shift使总的参数左移一位
shift one time: num: 3

 

 

 

 002、example 2

[root@pc1 test2]# ls
a.sh
[root@pc1 test2]# cat a.sh                      ## 测试程序
#!/bin/bash

until [ $# -eq 0 ]                              ## until条件测试语句,不满足条件($#总参数个数为0),循环体一直执行
do
        echo "第一个参数为: $1 参数个数为: $#"      ## 输出第一个参数和参数个数
        shift                                   ##  循环体执行一次,参数左移一次,总参数个数减少1
done
[root@pc1 test2]# bash a.sh 10 20 30            ## 执行程序, 一共执行了三次循环体,依次左移三次,参数个数$#为0时,循环结束
第一个参数为: 10 参数个数为: 3
第一个参数为: 20 参数个数为: 2
第一个参数为: 30 参数个数为: 1

 

003、example 3

[root@pc1 test2]# ls
a.sh
[root@pc1 test2]# cat a.sh
#!/bin/bash
if [ $# -le 0 ]; then            ## 条件判断,无参数时,退出程序
echo "Not enough parameters"
exit 1
fi
sum=0
while [ $# -gt 0 ]               ## 当有参数时,执行循环体,参数个数为0时,退出循环
do
sum=`expr $sum + $1`             ## 变量sum 对 参数递加
shift
done

echo $sum                        ## 输出所有参数的和
[root@pc1 test2]# bash a.sh 10 20 30
60

 

参考:

01、https://blog.csdn.net/dai9812/article/details/128702875

 

posted @ 2023-11-05 16:57  小鲨鱼2018  阅读(578)  评论(0编辑  收藏  举报