我需要帮助getopts
.
我创建了一个 Bash 脚本,运行时如下所示:
$ foo.sh -i env -d 目录 -s 子目录 -f 文件
当处理每个标志的一个参数时,它可以正常工作。但是,当我从每个标志调用多个参数时,我不确定如何从变量中提取多个变量信息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
获取选项后,我想从变量构建目录结构
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
有任何想法吗?
You can 多次使用相同的选项并将所有值添加到数组中.
对于这里非常具体的原始问题,Ryan 的mkdir -p
解决方案显然是最好的。
然而,对于更普遍的问题使用 getopts 从同一选项获取多个值, 这里是:
#!/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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)