首页 > 解决方案 > 在 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

标签: bashcommand-line-arguments

解决方案


在您的while循环之后,您需要shift输出任何选项及其参数。即使没有任何标志/标志争论,这也有效。

shift $(($OPTIND - 1))

然后其余的论点可用"$@"并且可以以任何通常的方式处理。例如:

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

有关更多信息,请在此处查看我的回答。


推荐阅读