Bash 脚本使用 getopts 将字符串存储为数组

标签 bash getopts

我正在开发一个 Bash 脚本,需要将零到多个字符串作为输入,但由于列表之前缺少标志,我不确定如何执行此操作。

脚本用法:

script [ list ] [ -t <secs> ] [ -n <count> ]

该列表接受零个、一个或多个字符串作为输入。当遇到空格时,在两个或多个字符串的情况下,它充当字符串之间的分隔符。这些字符串最终将被输入 grep 命令,所以我的想法是将它们保存在某种数组中。我目前的 -t-n 工作正常。我尝试查找示例,但无法找到与我想做的事情类似的任何内容。我的另一个问题是如何在设置标志后忽略字符串输入,以便不接受其他字符串。

我当前的脚本:

while getopts :t:n: arg; do
  case ${arg} in
    t)
      seconds=${OPTARG}
      if ! [[ $seconds =~ ^[1-9][0-9]*$ ]] ; then
        exit
      fi
      ;;
    n)
      count=${OPTARG}
      if ! [[ $count =~ ^[1-9][0-9]*$ ]] ; then
        exit
      fi
      ;;
    :)
      echo "$0: Must supply an argument to -$OPTARG" >&2
      exit
      ;;
    ?)
      echo "Invalid option: -${OPTARG}"
      exit
      ;;
  esac
done

编辑: 这是一项家庭作业,我不确定参数的顺序是否可以改变

编辑 2:选项可以按任意顺序排列

最佳答案

请您尝试以下操作:

#!/bin/bash

# parse the arguments before getopts
for i in "$@"; do
    if [[ $i = "-"* ]]; then
        break
    else                # append the arguments to "list" as long as it does not start with "-"
        list+=("$1")
        shift
    fi
done

while getopts :t:n: arg; do
    : your "case" code here
done

# see if the variables are properly assigned
echo "seconds=$seconds" "count=$count"
echo "list=${list[@]}"

关于Bash 脚本使用 getopts 将字符串存储为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71490881/

相关文章:

linux - getopts命令没有输入时如何回显

bash - 阅读 $OPTARG 以获得可选标志?

bash - 这是在 bash 中复制符号链接(symbolic link)目录的正确方法吗?

bash - 使用 ssh 读取一行后 while 循环退出

arrays - 如何检查数组的所有成员是否都等于 unix bash 中的某物

json - 在shell脚本中解析json数组

linux - getopts 没有将我的选项发送到标准输出

macos - -bash : : command not found when launching the shell in Mac OSX

bash - 如何在 Bash 中使用 getopts 允许非可选参数位于可选参数之前?

linux - 错误 : File not found with name : -a while using getopts