Bash 中的命令行参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12036445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:34:12  来源:igfitidea点击:

Command line arguments in Bash

bashcommand-line-arguments

提问by Pascal

I want to write a bash script which takes different arguments. It should be used like normal linux console programs:

我想编写一个采用不同参数的 bash 脚本。它应该像普通的 linux 控制台程序一样使用:

my_bash_script -p 2 -l 5 -t 20

So the value 2 should be saved in a variable called pages and the parameter l should be saved in a variable called length and the value 20 should be saved in a variable time.

因此,值 2 应保存在名为 pages 的变量中,参数 l 应保存在名为 length 的变量中,而值 20 应保存在变量 time 中。

What is the best way to do this?

做这个的最好方式是什么?

回答by Theodros Zelleke

Use the getoptsbuiltin:
here's a tutorial

使用getopts内置:
here's a tutorial

pages=  length=  time=

while getopts p:l:t: opt; do
  case $opt in
  p)
      pages=$OPTARG
      ;;
  l)
      length=$OPTARG
      ;;
  t)
      time=$OPTARG
      ;;
  esac
done

shift $((OPTIND - 1))

shift $((OPTIND - 1))shifts the command line parameters so that you can access possible arguments to your script, i.e. $1, $2, ...

shift $((OPTIND - 1))移动命令行参数,以便您可以访问脚本的可能参数,即 $1, $2, ...

回答by Jo So

Something along the lines of

类似的东西

pages=
length=
time=

while test $# -gt 0
do
    case  in
        -p)
            pages=
            shift
            ;;
        -l)
            length=
            shift
            ;;
        -t)
            time=
            shift
            ;;
        *)
            echo >&2 "Invalid argument: "
            ;;
    esac
    shift
done