我正在开发一个 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/