如何处理复杂的 bash 参数?

如何处理复杂的 bash 参数?

我如何使用像来自 bash-hackers wiki 的“术语示例”,但演示之后并未涵盖它。

mybackup -x -f /etc/mybackup.conf -r ./foo.txt ./bar.txt

These are all positional parameters, but they can be divided into several logical groups:

    -x is an option (aka flag or switch). It consists of a dash (-) followed by one character.
    -f is also an option, but this option has an associated option argument (an argument to the option -f): /etc/mybackup.conf. The option argument is usually the argument following the option itself, but that isn't mandatory. Joining the option and option argument into a single argument -f/etc/mybackup.conf is valid.
    -r depends on the configuration. In this example, -r doesn't take arguments so it's a standalone option like -x.
    ./foo.txt and ./bar.txt are remaining arguments without any associated options. These are often used as mass-arguments. For example, the filenames specified for cp(1), or arguments that don't need an option to be recognized because of the intended behavior of the program. POSIX® calls them operands.

To give you an idea about why getopts is useful, The above command line is equivalent to:

mybackup -xrf /etc/mybackup.conf ./foo.txt ./bar.txt

答案1

查找 bash 内置命令获取选项. 它是一个高级命令行解析器,可以更轻松地使用 bash 脚本中的选项、参数和操作数。

网上有很多教程getopts。我建议在线搜索“bash getopts”,这样你就不会得到 C/C++ 结果(C/C++ 程序员经常使用一个具有相同名称、几乎相同用法的工具来实现相同的目的,但代码语法是 C-ish)。

例如,本教程涵盖了定义中提到的所有不同参数类型:https://www.stackchief.com/tutorials/Bash%20Tutorial%3A%20getopts

相关内容