| 1 | [[PageOutline]] |
| 2 | |
| 3 | = Shell = |
| 4 | シェルプログラミングはどこかに落とし穴がありそうで怖い. |
| 5 | |
| 6 | == 依存性を持つ関数呼び出し == |
| 7 | * {{{dep.sh}}} |
| 8 | {{{ |
| 9 | #!sh |
| 10 | #!/bin/sh |
| 11 | |
| 12 | function die () |
| 13 | { |
| 14 | local stat=$1 |
| 15 | local msg=$2 |
| 16 | |
| 17 | echo "${msg}: ${stat}" 1>&2 |
| 18 | exit ${stat} |
| 19 | } |
| 20 | |
| 21 | function _depnum () |
| 22 | { |
| 23 | local tgt=$1 |
| 24 | |
| 25 | for ((i=${#CHAIN[@]}; i >= 0; i--)); do |
| 26 | if [ "x${tgt}" = "x${CHAIN[$i]}" ]; then |
| 27 | echo $i |
| 28 | exit 0 |
| 29 | fi |
| 30 | done |
| 31 | |
| 32 | die 15 "ERR: no such target: ${tgt}" |
| 33 | } |
| 34 | |
| 35 | function run () |
| 36 | { |
| 37 | if [ -z "$CHAIN" ]; then |
| 38 | die 33 "\`\$CHAIN' not declared" |
| 39 | fi |
| 40 | |
| 41 | local tgt=$1 |
| 42 | local arg=$2 |
| 43 | local dnum=`_depnum ${tgt}` |
| 44 | |
| 45 | for ((i=0; i <= ${dnum}; i++)); do |
| 46 | arg="`${CHAIN[$i]} ${arg}`" |
| 47 | done |
| 48 | |
| 49 | if [ -n "${arg}" ]; then |
| 50 | echo ${arg} |
| 51 | fi |
| 52 | } |
| 53 | }}} |
| 54 | |
| 55 | * {{{dop.sh}}} |
| 56 | {{{ |
| 57 | #!sh |
| 58 | #!/bin/sh |
| 59 | |
| 60 | source dep.sh |
| 61 | |
| 62 | function clean () |
| 63 | { |
| 64 | echo "arg_clean: $1" 1>&2 |
| 65 | echo "cleaned" |
| 66 | } |
| 67 | |
| 68 | function pack () |
| 69 | { |
| 70 | echo "arg_pack: $1" 1>&2 |
| 71 | echo "packed" |
| 72 | } |
| 73 | |
| 74 | function upload () |
| 75 | { |
| 76 | echo "arg_upload: $1" 1>&2 |
| 77 | echo "uploaded" |
| 78 | } |
| 79 | |
| 80 | CHAIN=(clean pack upload) |
| 81 | |
| 82 | if [ $# -eq 1 ]; then |
| 83 | res=`run $1 init` |
| 84 | echo |
| 85 | echo "result: ${res}" |
| 86 | else |
| 87 | die 24 "syntax error" |
| 88 | fi |
| 89 | }}} |
| 90 | |
| 91 | * 実行結果 |
| 92 | {{{ |
| 93 | #!sh |
| 94 | $ sh dop.sh upload |
| 95 | arg_clean: init |
| 96 | arg_pack: cleaned |
| 97 | arg_upload: packed |
| 98 | |
| 99 | result: uploaded |
| 100 | |
| 101 | $ sh dop.sh pack |
| 102 | arg_clean: init |
| 103 | arg_pack: cleaned |
| 104 | |
| 105 | result: packed |
| 106 | |
| 107 | $ sh dop.sh clean |
| 108 | arg_clean: init |
| 109 | |
| 110 | result: cleaned |
| 111 | }}} |