BASH - $@ 中包含的选项

BASH - Options included in $@

我有一个处理文件并可以接受多个文件参数的脚本:

sh remove_engine file1 #single arg

sh remove_engine file1 file2 #multiple file arg

在脚本的顶部,我将它们与 $@ 收集在一起,以便遍历它们。

问题是我还将使用选项(以及 getopts)...

sh remove_engine -ri file1 file2

...和 ​​$@ 现在 returns

-rvi file1 file2

脚本的其余部分将 -ri 作为文件名。

也在脚本顶部附近,我有一个 while 循环 getopts

while getopts :rvi opt
do
    case"$opt" in
    v)      verbose="true";;
    i)      interactive="true";;
    r)      recursive="true";;
   [?])     echo "Usage..."
            exit;;
    esac
done

如何解析选项,然后从选项中分离出参数?

来自man bash

When the end of options is encountered, getopts exits with a return value greater than zero. OPTINDis set to the index of the first non-option argument, and name is set to ?.

所以完整的代码是:

#!/bin/bash

while getopts :rvi opt; do
  case $opt in
    v) verbose=true ;;
    i) interactive=true ;;
    r) recursive=true ;;
    *) echo "Usage..."; exit 1 ;;
  esac
done

shift $((OPTIND-1))  # remove all the OPTIND-1 parsed arguments from "$@"

echo "$@"  # use the remaining arguments