如何在Bash中获取带有标志的参数 [英] How to get arguments with flags in Bash

查看:87
本文介绍了如何在Bash中获取带有标志的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以在bash中轻松获得像这样的定位参数:

I know that I can easily get positioned parameters like this in bash:

$0$1

我希望能够使用这样的标志选项来指定每个参数的用途:

I want to be able to use flag options like this to specify for what each parameter is used:

mysql -u user -h host

按标志而不是按位置获取-u param-h param值的最佳方法是什么?

What is the best way to get -u param value and -h param value by flag instead of by position?

推荐答案

这是我通常使用的成语:

This is the idiom I usually use:

while test $# -gt 0; do
  case "$1" in
    -h|--help)
      echo "$package - attempt to capture frames"
      echo " "
      echo "$package [options] application [arguments]"
      echo " "
      echo "options:"
      echo "-h, --help                show brief help"
      echo "-a, --action=ACTION       specify an action to use"
      echo "-o, --output-dir=DIR      specify a directory to store output in"
      exit 0
      ;;
    -a)
      shift
      if test $# -gt 0; then
        export PROCESS=$1
      else
        echo "no process specified"
        exit 1
      fi
      shift
      ;;
    --action*)
      export PROCESS=`echo $1 | sed -e 's/^[^=]*=//g'`
      shift
      ;;
    -o)
      shift
      if test $# -gt 0; then
        export OUTPUT=$1
      else
        echo "no output dir specified"
        exit 1
      fi
      shift
      ;;
    --output-dir*)
      export OUTPUT=`echo $1 | sed -e 's/^[^=]*=//g'`
      shift
      ;;
    *)
      break
      ;;
  esac
done

关键点是:

  • $#是参数数量
  • while循环查看提供的所有参数,并在case语句中匹配它们的值
  • shift使第一个离开.您可以在case语句中多次移动以采用多个值.
  • $# is the number of arguments
  • while loop looks at all the arguments supplied, matching on their values inside a case statement
  • shift takes the first one away. You can shift multiple times inside of a case statement to take multiple values.

这篇关于如何在Bash中获取带有标志的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆