Linux脚本编写基础(五)

实例)

现在我们来讨论编写一个脚本的一般步骤。任何优秀的脚本都应该具有帮助和输入参数。并且写一个伪脚本(framework.sh),该脚本包含了大多数脚本都需要的框架结构,是一个非常不错的主意。这时候,在写一个新的脚本时我们只需要执行一下copy命令:

cp framework.sh myscript

然后再插入自己的函数。

让我们再看两个例子:

二进制到十进制的转换

脚本b2d 将二进制数 (比如 1101) 转换为相应的十进制数。这也是一个用expr命令进行数学运算的例子:

 

#!/bin/sh 
# vim: set sw=4 ts=4 et: 
help() 
{ 
cat < 
b2h -- convert binary to decimal 
USAGE: b2h [-h] binarynum 
OPTIONS: -h help text 
EXAMPLE: b2h 111010 
10  will return 58 
11  HELP 
12  exit 0 
13  } 
14  error() 
15  { 
16  # print an error and exit 
17  echo "$1" 
18  exit 1 
19  } 
20  lastchar() 
21  { 
22  # return the last character of a string in $rval 
23  if [ -z "$1" ]; then 
24  # empty string 
25  rval="" 
26  return 
27  fi 
28  # wc puts some space behind the output this is why we need sed: 
29  numofchar=`echo -n "$1" | wc -c | sed 's/ //g' ` 
30  # now cut out the last char 
31  rval=`echo -n "$1" | cut -b $numofchar` 
32  }
33   
34  chop() 
35  { 
36  # remove the last character in string and return it in $rval 
37  if [ -z "$1" ]; then 
38  # empty string 
39  rval="" 
40  return 
41  fi 
42  # wc puts some space behind the output this is why we need sed: 
43  numofchar=`echo -n "$1" | wc -c | sed 's/ //g' ` 
44  if [ "$numofchar" = "1" ]; then 
45  # only one char in string 
46  rval="" 
47  return 
48  fi 
49  numofcharminus1=`expr $numofchar "-" 1` 
50  # now cut all but the last char: 
51  rval=`echo -n "$1" | cut -b 0-${numofcharminus1}` 
52  } 
53  while [ -n "$1" ]; do 
54  case $1 in 
55  -h) help;shift 1;; # function help is called 
56  --) shift;break;; # end of options 
57  -*) error "error: no such option $1. -h for help";; 
58  *) break;; 
59  esac 
60  done 
61  # The main program 
62  sum=0 
63  weight=1 
64  # one arg must be given: 
65  [ -z "$1" ] && help 
66  binnum="$1" 
67  binnumorig="$1"
68   
69  while [ -n "$binnum" ]; do 
70  lastchar "$binnum" 
71  if [ "$rval" = "1" ]; then 
72  sum=`expr "$weight" "+" "$sum"` 
73  fi 
74  # remove the last position in $binnum 
75  chop "$binnum" 
76  binnum="$rval" 
77  weight=`expr "$weight" "*" 2` 
78  done 
79  echo "binary $binnumorig is decimal $sum" 
80   

 

该脚本使用的算法是利用十进制和二进制数权值 (1,2,4,8,16,..),比如二进制"10"可以这样转换成十进制:

0 * 1 + 1 * 2 = 2

为了得到单个的二进制数我们是用了lastchar 函数。该函数使用wc –c计算字符个数,然后使用cut命令取出末尾一个字符。Chop函数的功能则是移除最后一个字符。

你可能感兴趣的:(linux)