萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> Shell腳本傳遞參數的3種方法比較

Shell腳本傳遞參數的3種方法比較

   這篇文章主要介紹了Shell腳本傳遞參數的3種方法比較,本文直接給出代碼示例,在代碼中包含詳細注解,需要的朋友可以參考下

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 #!/bin/bash #extracting command text_text_text_line options as parameters   help_info(){ echo "NAME" echo "t$0" echo "SYNOPSIS" echo "t$0 is a shell test about process options" echo "DESCRIPTION" echo "toption like -a -b param1 -c param2 -d" }   if [ $# -lt 0 ] then help_info fi   nomal_opts_act() { echo -e "n### nomal_opts_act ###n"   while [ -n "$1" ] do case "$1" in -a) echo "Found the -a option" ;; -b) echo "Found the -b option" echo "The parameter follow -b is $2" shift ;; -c) echo "Found the -c option" echo "The parameter follow -c is $2" shift ;; -d) echo "Found the -d option" ;; *) echo "$1 is not an option" ;; esac shift done }   #用shell命令自建的選項解析,可以按照自己的想法實現 #優點:自己定制,沒有做不到,只有想不到 #缺點:麻煩   getopt_act() { echo -e "n### getopt_act ###n"   GETOPTOUT=`getopt ab:c:d "$@"` set -- $GETOPTOUT while [ -n "$1" ] do case $1 in -a) echo "Found the -a option" ;; -b) echo "Found the -b option" echo "The parameter follow -b is "$2"" shift ;; -c) echo "Found the -c option" echo "The parameter follow -c is "$2"" shift ;; -d) echo "Found the -d option" ;; --) shift break ;; *) echo "Unknow option: "$1"" ;; esac shift done   param_index=1 for param in "$@" do echo "Parameter $param_index:$param" param_index=$[ $param_index + 1 ] done }   #用getopt命令解析選項和參數 #優點:相對與getopts來說是個半自動解析,自動組織選項和參數,用 -- 符號將選項與參數隔開 #缺點:相對於getopts的缺點 #1.需要與set -- 命令配合,不是必須,需要手動shift #2.選項參數中不支持空格如 -a -b dog -c "earth moon" -d -f param1 param2 就會解析錯誤   getopts_act() { echo -e "n### getopts_act ###n" while getopts :ab:c:d ARGS do case $ARGS in a) echo "Found the -a option" ;; b) echo "Found the -b option" echo "The parameter follow -b is $OPTARG" ;; c) echo "Found the -c option" echo "The parameter follow -c is $OPTARG" ;; d) echo "Found the -d option" ;; *) echo "Unknow option: $ARGS" ;; esac done   shift $[ $OPTIND -1 ] param_index=1 for param in "$@" do echo "Parameter $param_index:$param" param_index=$[ $param_index + 1 ] done }   #getopts 命令解析選項和參數 #優點:可在參數中包含空格如:-c "earth moon" # 選項字母和參數值之間可以沒有空格如:-bdog # 可將未定義的選項綁定到?輸出 # Unknow option: ?   nomal_opts_act -a -b dog -c earth -d -f param1 param2 getopts_act -a -b dog -c "earth moon" -d -f param1 param2 getopt_act -a -b dog -c earth -d -f param1 param2

        注< >:更多精彩教程請關注三聯編程

copyright © 萬盛學電腦網 all rights reserved