shell中while的使用 (ex26.sh,ex26a.sh)

本文详细介绍了bash脚本中使用while循环结合读取变量的功能,通过实例演示了如何在循环中输入变量并判断终止条件,同时展示了脚本如何跟踪和处理变量变化。
#!/bin/bash

echo
                               # Equivalent to:
while [ "$var1" != "end" ]     # while test "$var1" != "end"
do
  echo "Input variable #1 (end to exit) "
  read var1                    # Not 'read $var1' (why?).
  echo "variable #1 = $var1"   # Need quotes because of "#" . . .
  # If input is 'end', echoes it here.
  # Does not test for termination condition until top of loop.
  echo
done  

exit 0

[root@localhost shell]# ./ex26.sh

Input variable #1 (end to exit)
aa
variable #1 = aa

Input variable #1 (end to exit)
bb
variable #1 = bb

Input variable #1 (end to exit)
end

variable #1 = end

#!/bin/bash

var1=unset
previous=$var1

while echo "previous-variable = $previous"
      echo
      previous=$var1
      [ "$var1" != end ] # Keeps track of what $var1 was previously.
      # Four conditions on "while", but only last one controls loop.
      # The *last* exit status is the one that counts.
do
echo "Input variable #1 (end to exit) "
  read var1
  echo "variable #1 = $var1"
done  

# Try to figure out how this all works.
# It's a wee bit tricky.

exit 0
[root@localhost shell]# ./ex26a.sh
previous-variable = unset

Input variable #1 (end to exit)
aa
variable #1 = aa
previous-variable = unset

Input variable #1 (end to exit)
bb
variable #1 = bb
previous-variable = aa

Input variable #1 (end to exit)
cc
variable #1 = cc
previous-variable = bb

Input variable #1 (end to exit)
end
variable #1 = end
previous-variable = cc





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值