Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在bash脚本中,在命令行的选项之前使用可选参数_Bash_Shell_Unix_Command Line Arguments_Getopts - Fatal编程技术网

在bash脚本中,在命令行的选项之前使用可选参数

在bash脚本中,在命令行的选项之前使用可选参数,bash,shell,unix,command-line-arguments,getopts,Bash,Shell,Unix,Command Line Arguments,Getopts,我有一个脚本myscript,它应该执行以下操作: 独立运行:myscript 使用参数运行:myscript myarg 使用以下选项运行:myscript-a1-b2-c3… 使用参数和选项运行:myscript myarg-a1-b2-c3… 我拿不到4。在选项前面使用参数(我从getopts中获取)似乎会干扰getopts处理一切的方式 我使用的代码基本上是这样的: while getopts "a:b:c:" opt; do case ${opt} in a)

我有一个脚本
myscript
,它应该执行以下操作:

  • 独立运行:
    myscript
  • 使用参数运行:
    myscript myarg
  • 使用以下选项运行:
    myscript-a1-b2-c3…
  • 使用参数和选项运行:
    myscript myarg-a1-b2-c3…
  • 我拿不到4。在选项前面使用参数(我从
    getopts
    中获取)似乎会干扰
    getopts
    处理一切的方式

    我使用的代码基本上是这样的:

    while getopts "a:b:c:" opt; do
       case ${opt} in
          a)
             var_a=$OPTARG
             ;;
          ... more options here
       esac
    done
    
    if [ ! -z "$1" ] && [[ ! "$1" =~ ^- ]]; then
          ... do stuff with first argument - if it's there and it's not just an option
    fi
    

    如果这个问题有一个简单的解决方案,我将非常感谢

    您可以在脚本的最后一个
    if
    中使用
    shift

    您是否想过使用shift来摆脱第一个参数?这确实非常简单,谢谢!我猜这个问题可以结束了,你想把它作为答案发布吗?还是我应该写一个答案?解决方案的一个潜在缺点是:
    if[condition],然后。。。转移在调用
    getopts
    之前必须使用fi
    ,这可能是一个问题(但在我的情况下不是)。除非您想支持
    myscript-a1 myarg-b2-c3
    ,否则如果[[$1==myarg]],运行
    不会有问题;然后转移。。。;fi
    getopts
    循环之前。