在 bash 中解析命令行参数和标志的组合

Parse combination of command-line arguments and flags in bash

我正在尝试编写 bash 脚本,它将读取多个文件名和一个目标目录,这是可选的。

./myfile -t /home/users/ file1 file2

我试过以下代码,但我无法处理下面提到的不同情况:

while getopts "t:" opt; do
  case $opt in
    t)
      echo "-t was triggered, Parameter: $OPTARG"
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument."
      exit 1
      ;;
  esac
done

但是代码应该处理不同的场景,例如: ./myfile file1 file2 -t /home/users/, ./myfile file1 -t /home/users/ file2 file3, ./myfile file1 file2 file3 file4 并且应该能够读取文件。

在这种情况下,使用 while 循环到 readshift 参数可能更容易。 在下面的示例中,循环遍历参数以查找字符串 -t 在这种情况下,参数数组移动了一步,现在 nr 1 索引应该是可选的 homedir。在所有其他情况下,该项目被移动到另一个名为 files.

的数组
#! /bin/bash

files=()
homedir=
while (( $# > 0 )); do
    case "" in
        -t )
            shift
            homedir=""
            ;;
        * )
            files+=("")
        ;;
    esac
    shift
done
echo "${files[@]}"
echo "$homedir"

while 循环之后,您需要 shift 输出任何选项及其参数。即使没有任何 flags/flag 争论,这仍然有效。

shift $(($OPTIND - 1))

然后其余的参数在 "$@" 中可用,并且可以用任何通常的方式处理。例如:

for arg in "$@"
do
    something_with "$arg"
done

有关更多信息,请参阅我的回答 here