【问题标题】:Including sub-parameters in help options to execute wisely?在帮助选项中包含子参数以明智地执行?
【发布时间】:2013-05-03 16:36:45
【问题描述】:

我正在编写一个可以选择文件并打印特定内容的脚本。例如,

san#./script.sh

Expected Usage : ./script.sh --file1 --dns

(这里检查file1,搜索dns名称并打印。基本上一个参数下有子参数)

我尝试了如下的单个参数/选项:

options=$@

arguments=($options)

index=0;
for argument in $options
do
    index=`expr $index + 1`;
    case $argument in
    -a | --fun1 ) run_function1 ;;
    -b | --fun2 ) run_function2 ;;
    -c | --fun3 ) run_function3 ;;
    esac
done
exit;

[ ${1} ] || helpinfo

任何人都可以建议双参数(子选项)吗?

预期的目标选项:

./script.sh


OPTIONS : ./script.sh -h

./script --fun1 stackoverflow
        microsoft
        Google
     --fun2 Yahoo 

基本上每个函数都会查看一个文件。我研究了 getopt 或 getopts,但它没有长选项(--long 是不可能的,相反我们只能使用-l)。但再次不确定子参数。有人可以帮忙吗?

【问题讨论】:

标签: linux bash shell unix scripting


【解决方案1】:

我不确定我是否正确理解你......但让我们试试我的运气:)

$ cat a.sh
#!/bin/bash

function fun1 {
   echo "fun1 '$1'"
}

function fun2 {
   echo "fun2 '$1'"
}

function err {
   echo "No function has been specified"
   exit 1
}

FUNCTION=err
while [ $# -gt 0 ]; do
   case "$1" in
      -a | --fun1 ) FUNCTION=fun1 ;;
      -b | --fun2 ) FUNCTION=fun2 ;;
      *) $FUNCTION "$1" ;;
   esac
   shift
done

$ ./a.sh --fun1 one two -b three
fun1 'one'
fun1 'two'
fun2 'three'

【讨论】:

    【解决方案2】:

    有一个关于参数解析的详细FAQ(包括你所谓的“子选项”):http://mywiki.wooledge.org/BashFAQ/035

    【讨论】:

    • 我没有找到很多细节可以在我的场景中实现。你能从上面的细节中给我一个示例代码吗?谢谢!
    猜你喜欢
    • 2018-07-07
    • 1970-01-01
    • 2011-07-12
    • 2010-12-20
    • 2021-01-19
    • 2021-09-16
    • 2015-12-09
    • 2011-04-26
    • 1970-01-01
    相关资源
    最近更新 更多