例項)
現在我們來討論編寫一個指令碼的一般步驟。任何優秀的指令碼都應該具有幫助和輸入引數。並且寫一個偽指令碼(framework.sh),該指令碼包含了大多數指令碼都需要的框架結構,是一個非常不錯的主意。這時候,在寫一個新的指令碼時我們只需要執行一下copy命令:
cp framework.sh myscript
然後再插入自己的函式。
讓我們再看兩個例子:
二進位制到十進位制的轉換
指令碼b2d 將二進位制數 (比如 1101) 轉換為相應的十進位制數。這也是一個用expr命令進行數學運算的例子:
1 | #!/bin/sh |
2 | # vim: set sw=4 ts=4 et: |
3 | help() |
4 | { |
5 | cat < |
6 | b2h -- convert binary to decimal |
7 | USAGE: b2h [-h] binarynum |
8 | OPTIONS: -h help text |
9 | 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函式的功能則是移除最後一個字元。