zoukankan      html  css  js  c++  java
  • [Bash] Create a Bash Script that Accepts Named Options with getopts

    Getopts

    Let’s say you want to allow a user to pass a -v flag to turn on verbose logging in a script. Manually parsing out options passed to a script is difficult, but in this lesson, we’ll learn about getopts which makes it easy. We'll look at the limitations of using getopts (options must be in a format like -a or -ab ) as well as the importance of shifting processed options off of the argument array.

    ## ':a': if the opt is a
    ## 'b:' if the opt is b and it has value as well
    ## '$OPTARG': is the value that passed in
    ## '?': catch unknown opt
    while getopts ':ab:' opt; do
        case "$opt" in
            a) echo "a found";;
            b) echo "b found and the value is $OPTARG";;
            ?) echo "unknow option";;
        esac
    done
    

    If we run it with:

    ./getopts.sh -a -b 123
    ## a found
    ## b found and the value is 123
    

    If we run with some extra options we didn't handle:

    bash % ./getopts.sh -a -b 123 -d -e -f 321
    ## a found
    ## b found and the value is 123
    ## unknow option
    ## unknow option
    ## unknow option
    

    Shift

    Remove the args we have processed.

    ## ':a': if the opt is a
    ## 'b:' if the opt is b and it has value as well
    ## '$OPTARG': is the value that passed in
    ## '?': catch unknown opt
    while getopts ':ab:' opt; do
        case "$opt" in
            a) echo "a found";;
            b) echo "b found and the value is $OPTARG";;
            ?) echo "unknow option";;
        esac
    done
    
    shift $(( OPTIND -1 ))
    
    for arg in $@; do
        echo "received arg $arg"
    done 
    

    If run it with:

    ./getopts.sh -a -b 123 abc def tsf 
    
    ## a found
    ## b found and the value is 123
    ## received arg abc
    ## received arg def
    ## received arg tsf
    
  • 相关阅读:
    JavaScript 用new创建对象的过程
    从输入URL到浏览器显示页面发生了什么
    JS中的this对象详解
    JS事件
    vue如何正确销毁当前组件的scroll事件?
    pg创建存储过程批量提交
    mysql去掉明文密码不安全提示
    解决npm安装node-sass太慢及编译错误问题
    解决vs code编写python输出中文乱码问题
    EditPlus配置Java编译器
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14398914.html
Copyright © 2011-2022 走看看