BASH:getopts的从一个标志检索多个变量 [英] BASH: getopts retrieving multiple variables from one flag
问题描述
我卡住,需要你的帮助球员与getops
I am stuck and need your guys help with with getops
我创建了一个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
处理来自各个标志一个参数,当它正常工作。但是,当我envoke几个arguements从每个标志我不知道如何把多个varibale信息出变量的getops。
It works correctly when handling one argument from each flag. But when I envoke several arguements from each flag I am not sure how to pull the multiple varibale information out of the variables in getops.
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
接着的目录结构将是
Then the directory structure would be
/test/directory/subdirectory/file1
/test/directory/subdirectory/file2
/test/directory/subdirectory/file3
/test/directory/subdirectory2/file1
/test/directory/subdirectory2/file2
/test/directory/subdirectory2/file3
任何想法?
推荐答案
您可以使用同一选项多次和所有值添加到一个数组
对于这里的非常具体的原题,瑞安的的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屋!