指定参数的shell脚本

通过执行脚本的时候使用 --<parameter> 的形式,把变量传进脚本,与参数位置无关。

#!/bin/bash
# Tue Dec 17 CST 2019


# help options
usage () {
    cat <<EOF
Usage: $0 [OPTIONS]
  --version=19.0.0    Specify the version
  --file=file         The specified file
  --home=homedir      The specified directory
EOF
  exit 1
}

parse_arguments() {
  # Read the parameter
  for arg do 
  # the parameter after "=", or the whole $arg if no match
  val=`echo "$arg" | sed -e 's;^--[^=]*=;;'`
  # what's before "=", or the whole $arg if no match
  optname=`echo "$arg" | sed -e 's/^\(--[^=]*\)=.*$/\1/'`
  # replace "_" by "-" 
  optname_subst=`echo "$optname" | sed 's/_/-/g'`
  arg=`echo $arg | sed "s/^$optname/$optname_subst/"`   
    case "$arg" in       
      --version=*) version="$val" ;;
      --file=*) file="$val" ;;
      --home=*) home="$val" ;;
      --help) usage ;;
      *) shell_quote_string "$arg" ;;
    esac
  done
}
shell_quote_string() {
  # This sed command makes sure that any special chars are quoted,
  # so the arg gets passed exactly to the server.
  echo "$1" | sed -e 's,\([^a-zA-Z0-9/_.=-]\),\\\1,g'
}

parse_arguments "$@"

if test -n "$version"
then
  echo "version: $version"
fi

if test -n "$file"
then
  echo "file: $file"
fi

if test -n "$home"
then
  echo "home: $home"
fi

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值