本文介绍了在bash中使用getopts的布尔cli标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在bash中使用getopts实现布尔cli选项?基本上,如果要指定 -x ,我想做一件事,如果没有指定,我想做另一件事.

Is it possible to implement a boolean cli option using getopts in bash? Basically I want to do one thing if -x is specified and another if it is not.

推荐答案

当然可以.@JonathanLeffler已经在问题的注释中给出了答案,所以我在这里要做的只是添加一个实现示例和一些要考虑的细节:

Of course it is possible. @JonathanLeffler already pretty much gave the answer in the comments to the question, so all I'm going to do here is add an example of the implementation and a few niceties to consider:

#!/usr/bin/env bash

# Initialise option flag with a false value
OPT_X='false'

# Process all options supplied on the command line 
while getopts ':x' 'OPTKEY'; do
    case ${OPTKEY} in
        'x')
            # Update the value of the option x flag we defined above
            OPT_X='true'
            ;;
        '?')
            echo "INVALID OPTION -- ${OPTARG}" >&2
            exit 1
            ;;
        ':')
            echo "MISSING ARGUMENT for option -- ${OPTARG}" >&2
            exit 1
            ;;
        *)
            echo "UNIMPLEMENTED OPTION -- ${OPTKEY}" >&2
            exit 1
            ;;
    esac
done

# [optional] Remove all options processed by getopts.
shift $(( OPTIND - 1 ))
[[ "${1}" == "--" ]] && shift

# "do one thing if -x is specified and another if it is not"
if ${OPT_X}; then
    echo "Option x was supplied on the command line"
else
    echo "Option x was not supplied on the command line"
fi

有关上述示例的一些注意事项:

A few notes about the above example:

  • true false 用作选项x指示符,因为它们都是有效的UNIX命令.我认为,这使得对选项存在状态的测试更具可读性.

  • true and false are used as option x indicators because both are valid UNIX commands. This makes the test for the option presence more readable, in my opinion.

getopts 配置为以静默错误报告模式运行,因为它抑制了默认错误消息并允许更精确的错误处理.

getopts is configured to run in silent error reporting mode because it suppressed default error messages and allows for a more precise error handling.

该示例包含用于处理缺少的选项参数和post-getopts命令行参数的代码片段.这些都不是OP的问题.

the example includes fragments of code for dealing with missing option arguments and post-getopts command line arguments. These are not part of the OP's question.

添加它们是为了完整性,因为在任何相当复杂的脚本中都需要此代码.

They are added for the sake of completeness as this code will be required in any reasonably complex script.

有关 getopts 的更多信息,请参见 Bash Hackers Wiki:小型getopts教程

For more information about getopts see Bash Hackers Wiki: Small getopts tutorial

这篇关于在bash中使用getopts的布尔cli标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 17:48