【问题标题】:Combining multiple options into one single option (Getopts)将多个选项组合成一个选项(Getopts)
【发布时间】:2018-09-30 22:42:51
【问题描述】:

由于我对getopts的理解不够透彻,所以标题肯定是模糊的:0。我目前正在编写一个 bash 脚本,我想在 getopts 的 case 语句中添加一个输出其他选项的选项。为了扩展,我把程序缩短了。

#!/bin/bash

while getopts :abc opt
do
  case $opt in
       a) 
           echo "Hello"
           ;;
       b)
           echo "Goodbye"
       c)            
           :ab #****I WANT -c TO OUTPUT THE RESULTS OF a and b************
           ;;
esac
done

正如您在选项 c 中看到的,我希望这个特定选项 (-c) 能够同时输出 -a 和 -b 的结果。有没有办法通过简单地对选项 a 和 b 进行 c 调用来解决这个问题?

【问题讨论】:

    标签: linux bash scripting options getopts


    【解决方案1】:

    如果您使用的是最新版本的 Bash,而不是使用 ;; 终止 case 子句,您可以使用具有多种模式的 bash 特定 ;;&

    #!/bin/bash
    
    while getopts :abc opt
    do
        case $opt in
            a|c) 
                echo "Hello"
                ;;&
            b|c)
                echo "Goodbye"
                ;;&
        esac
    done
    

    还有:

    $ bash script.bash -a
    Hello
    $ bash script.bash -c 
    Hello
    Goodbye
    

    Using ‘;;&’ in place of ‘;;’ causes the shell to test the patterns in the next clause, if any, and execute any associated command-list on a successful match.

    【讨论】:

      【解决方案2】:

      你可以引入函数来减少重复,像这样:

      #!/bin/bash
      
      do_a() {
        echo "Hello"
      }
      
      do_b() {
        echo "Goodbye"
      }
      
      
      while getopts :abc opt
      do
        case $opt in
           a)
               do_a
               ;;
           b)
               do_b
               ;;
           c)    
               do_a
               do_b
               ;;
        esac
      done
      

      【讨论】:

        猜你喜欢
        • 2021-06-23
        • 2016-09-03
        • 2013-04-17
        • 2012-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多