在Bash中使用getopts检索单个选项的多个参数 [英] Retrieving multiple arguments for a single option using getopts in Bash
问题描述
我需要有关getopts
的帮助.
我创建了一个Bash脚本,运行时如下所示:
I created a Bash script which looks like this when run:
$ foo.sh -i env -d目录-s子目录-f文件
$ foo.sh -i env -d directory -s subdirectory -f file
当处理每个标志的一个参数时,它可以正常工作.但是,当我从每个标志调用多个参数时,我不确定如何从getopts
中的变量中提取多个变量信息.
It works correctly when handling one argument from each flag. But when I invoke several arguments from each flag I am not sure how to pull the multiple variable information out of the variables in getopts
.
while getopts ":i:d:s:f:" opt
do
case $opt in
i ) initial=$OPTARG;;
d ) dir=$OPTARG;;
s ) sub=$OPTARG;;
f ) files=$OPTARG;;
esac
done
在获取了选项之后,我想从变量中构建目录结构
After grabbing the options I then want to build directory structures from the variables
foo.sh -i test -d directory -s subdirectory -s subdirectory2 -f file1 file2 file3
然后目录结构为
/test/directory/subdirectory/file1
/test/directory/subdirectory/file2
/test/directory/subdirectory/file3
/test/directory/subdirectory2/file1
/test/directory/subdirectory2/file2
/test/directory/subdirectory2/file3
有什么想法吗?
推荐答案
您可以多次使用同一选项,并将所有值添加到数组中.
对于这里非常具体的原始问题,Ryan的mkdir -p
解决方案显然是最好的.
For the very specific original question here, Ryan's mkdir -p
solution is obviously the best.
但是,对于以下更普遍的问题:使用getopts从同一选项中获取多个值,它是:
However, for the more general question of getting multiple values from the same option with getopts, here it is:
#!/bin/bash
while getopts "m:" opt; do
case $opt in
m) multi+=("$OPTARG");;
#...
esac
done
shift $((OPTIND -1))
echo "The first value of the array 'multi' is '$multi'"
echo "The whole list of values is '${multi[@]}'"
echo "Or:"
for val in "${multi[@]}"; do
echo " - $val"
done
输出为:
$ /tmp/t
The first value of the array 'multi' is ''
The whole list of values is ''
Or:
$ /tmp/t -m "one arg with spaces"
The first value of the array 'multi' is 'one arg with spaces'
The whole list of values is 'one arg with spaces'
Or:
- one arg with spaces
$ /tmp/t -m one -m "second argument" -m three
The first value of the array 'multi' is 'one'
The whole list of values is 'one second argument three'
Or:
- one
- second argument
- three
这篇关于在Bash中使用getopts检索单个选项的多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!