Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1720177
  • 博文数量: 362
  • 博客积分: 10587
  • 博客等级: 上将
  • 技术积分: 4098
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-10 18:15
文章分类

全部博文(362)

文章存档

2014年(1)

2013年(58)

2011年(115)

2010年(112)

2009年(76)

分类:

2010-10-04 16:23:27

shift命令会重新分配位置参数, 其实就是把所有的位置参数都向左移动一个位置.

$1 <--- $2$2 <--- $3$3 <--- $4, 等等.

原来的$1就消失了, 但是$0 (脚本名)是不会改变的. 如果传递了大量的位置参数到脚本中, 那么shift命令允许你访问的位置参数的数量超过10个, 当然{}标记法也提供了这样的功能.

#!/bin/bash
# shft.sh: Using 'shift' to step through all the positional parameters.

#  Name this script something like shft.sh,
#+ and invoke it with some parameters.
#+ For example:
#             sh shft.sh a b c def 23 Skidoo

until [ -z "$1" ]  # Until all parameters used up . . .
do
  echo -n "$1 "
  shift
done

echo               # Extra linefeed.

# But, what happens to the "used-up" parameters?
echo "$2"
#  Nothing echoes!
#  When $2 shifts into $1 (and there is no $3 to shift into $2)
#+ then $2 remains empty.
#  So, it is not a parameter *copy*, but a *move*.

exit

#  See also the echo-params.sh script for a "shiftless"
#+ alternative method of stepping through the positional params.



接下来是另一个shift命令的应用

#!/bin/bash
# shift-past.sh

shift 3    # Shift 3 positions.
#  n=3; shift $n
#  Has the same effect.

echo "$1"

exit 0

# ======================== #


$ sh shift-past.sh 1 2 3 4 5
4

#  However, as Eleni Fragkiadaki, points out,
#+ attempting a 'shift' past the number of
#+ positional parameters ($#) returns an exit status of 1,
#+ and the positional parameters themselves do not change.
#  This means possibly getting stuck in an endless loop. . . .
#  For example:
#      until [ -z "$1" ]
#      do
#         echo -n "$1 "
#         shift 20    #  If less than 20 pos params,
#      done           #+ then loop never ends!
#
# When in doubt, add a sanity check. . . .
#           shift 20 || break
#                    ^^^^^^^^

阅读(1209) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~