如何使用 getopt(s) 作为在 bash 中传递参数的技术

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6834698/
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 20:48:19  来源:igfitidea点击:

how to use getopt(s) as technique for passing in argument in bash

bashunixshellgetoptgetopts

提问by jdamae

Can someone show me an example how to use getopts properly or any other technique that I would be able to pass in an argument? I am trying to write this in unix shell/bash. I am seeing there is getopt and getopts and not sure which is better to use. Eventually, I will build this out to add for more options.

有人可以向我展示一个如何正确使用 getopts 的示例,或者我可以在参数中传递的任何其他技术吗?我正在尝试在 unix shell/bash 中编写它。我看到有 getopt 和 getopts,但不确定哪个更好用。最终,我将构建它以添加更多选项。

In this case, I want to pass the filepath as input to the shell script and place a description in the case it wasn't entered correctly.

在这种情况下,我想将文件路径作为输入传递给 shell 脚本,并在未正确输入的情况下放置描述。

export TARGET_DIR="$filepath"

For example: (calling on the command line)

例如:(在命令行上调用)

./mytest.sh -d /home/dev/inputfiles

Error msg or prompt for correct usage if running it this way:

如果以这种方式运行,则会出现错误消息或提示正确使用:

./mytest.sh -d /home/dev/inputfiles/

回答by glenn Hymanman

As a user, I would be very annoyed with a program that gave me an error for providing a directory name with a trailing slash. You can just remove it if necessary.

作为用户,我会对一个程序感到非常恼火,该程序为我提供了一个带有斜杠的目录名错误。如有必要,您可以将其删除。

A shell example with pretty complete error checking:

一个带有非常完整的错误检查的 shell 示例:

#!/bin/sh

usage () {
  echo "usage: 
:)  echo "Error: -$OPTARG requires an argument"
-d dir_name" echo any other helpful text } dirname="" while getopts ":hd:" option; do case "$option" in d) dirname="$OPTARG" ;; h) # it's always useful to provide some help usage exit 0 ;; :) echo "Error: -$OPTARG requires an argument" usage exit 1 ;; ?) echo "Error: unknown option -$OPTARG" usage exit 1 ;; esac done if [ -z "$dirname" ]; then echo "Error: you must specify a directory name using -d" usage exit 1 fi if [ ! -d "$dirname" ]; then echo "Error: the dir_name argument must be a directory exit 1 fi # strip any trailing slash from the dir_name value dirname="${dirname%/}"

For getopts documentation, look in the bash manual

有关 getopts 文档,请查看bash 手册

回答by pBi

Correction to the ':)' line:

更正':)'行:

Error: -: requires an argument

because if no value got provided after the flag, then OPTARG gets the name of the flag and flag gets set to ":" which in the above sample printed:

因为如果在标志之后没有提供任何值,那么 OPTARG 将获取标志的名称,并将标志设置为“:”,在上面的示例中打印:

\?)  echo "Error: unknown option -$OPTARG"

which wasn't useful info.

这不是有用的信息。

Same applies to:

同样适用于:

##代码##

Thanks for this sample!

感谢您的样品!