命令行/Shell

shell的参数格式赋值及获取

2019-08-27  本文已影响0人  独孤流

Tips:
写shell脚本时有个很痛苦的事情,那就是传递参数时需要用1,2这种方式来获取,缺乏可读性,于是写了一个方法来从参数列表里读取出来

function parseParams()
{
  # 获取的key
    findKey=""
    #获取最后一个参数,表示取的key
    count=0
    for i in "$@"; do
      # echo ">>>> $i\n"
      count=`expr $count + 1`
      if [ $count == $# ]; then
        findKey="$i="
      fi
   done

   #取出对应的key所获取的值
    for var in $@
    do
        # echo $var
        if [[ $var =~ ^$findKey* ]]; then
          #打印查找到的内容
          echo ${var#*$findKey}
          return 0
        fi
    done
    return 0
}
#demo
function test()
{
   name=`parseParams $@ "--name"`
   age=`parseParams $@ "--age"`
   country=`parseParams $@ "--country"`
   echo "paramsOne:$1"
   echo "name: $name"
   echo "paramsTwo:$2"
   echo "age: $age"
   echo "paramsThree:$3"
   echo "country: $country"
}
test --name="哪吒 hello world" --age="19" --country="china"

paramsOne:--name=哪吒 hello world
name: 哪吒
paramsTwo:--age=19
age: 19
paramsThree:--country=china
country: china

#支持包含空格的字符串
function parseParams2()
{
  # 获取的key
    findKey=""
    #获取最后一个参数,表示取的key
    count=0
    for i in "$@"; do
      count=`expr $count + 1`
      if [ $count == $# ]; then
        findKey="$i"
      fi
   done

  #查找匹配的内容
   index=0
   param_key=""
   param_val=""
    for i in "$@"; do
      index=`expr $index + 1`
      if  [ $index -ge $count ]; then
        if  [ "$param_key" == "$findKey" ]; then
          echo $param_val
        fi
        return 0
      fi
      if [[ $i == *=*  ]]; then
        if  [ "$param_key" == "$findKey" ]; then
          echo $param_val
          return 0
        fi
         arr=(${i//=/ })
         param_key=${arr[0]}
         param_val=${i#*$param_key=}
      else
        param_val=`echo "$param_val $i"`
      fi
   done
}
function test2()
{
   name=`parseParams2 $@ "--name"`
   age=`parseParams2 $@ "--age"`
   country=`parseParams2 $@ "--country"`
   echo "paramsOne:$1"
   echo "name: $name"
   echo "paramsTwo:$2"
   echo "age: $age"
   echo "paramsThree:$3"
   echo "country: $country"
}
test2 --name="哪吒 hello world" --age="19" --country="china"

paramsOne:--name=哪吒 hello world
name: 哪吒 hello world
paramsTwo:--age=19
age: 19
paramsThree:--country=china
country: china

上一篇下一篇

猜你喜欢

热点阅读