CentOS详细安装之十七:Linux的简单shell脚本中进行计算(类型转换)

alwayshelloworld 2010-05-24

1 #!/bin/bash
  2 # int-or-string.sh: 整型还是字符串?
  3 
  4 a=2334                   # 整型.
  5 let "a += 1"
  6 echo "a = $a "           # a = 2335
  7 echo                     # 还是整型.
  8 
  9 
 10 b=${a/23/BB}             # 将"23"替换成"BB".
 11                          # 这将把变量b从整型变为字符串.
 12 echo "b = $b"            # b = BB35
 13 declare -i b             # 即使使用declare命令也不会对此有任何帮助.
 14 echo "b = $b"            # b = BB35
 15 
 16 let "b += 1"             # BB35 + 1 =
 17 echo "b = $b"            # b = 1
 18 echo
 19 
 20 c=BB34
 21 echo "c = $c"            # c = BB34
 22 d=${c/BB/23}             # 将"BB"替换成"23".
 23                          # 这使得变量$d变为一个整形.
 24 echo "d = $d"            # d = 2334
 25 let "d += 1"             # 2334 + 1 =
 26 echo "d = $d"            # d = 2335
 27 echo
 28 
 29 # null变量会如何呢?
 30 e=""
 31 echo "e = $e"            # e =
 32 let "e += 1"             # 算术操作允许一个null变量?
 33 echo "e = $e"            # e = 1
 34 echo                     # null变量将被转换成一个整型变量.
 35 
 36 # 如果没有声明变量会怎样?
 37 echo "f = $f"            # f =
 38 let "f += 1"             # 算术操作能通过么?
 39 echo "f = $f"            # f = 1
 40 echo                     # 未声明的变量将转换成一个整型变量.
 41 
 42 
 43 
 44 # 所以说Bash中的变量都是不区分类型的.
 45 
 46 exit 0

相关推荐