【发布时间】:2014-04-29 09:02:35
【问题描述】:
我正在尝试为多个输入数据文件制作脚本。最好的方法是什么,如何处理这些论点?脚本的用法应该是:
./script.sh -a sth -b sth - c sth -d sth input1 input2 input3
我可以使用 getopts 处理参数和参数,但我不知道如何处理这些输入文件,因为它们没有标志。 谢谢
【问题讨论】:
我正在尝试为多个输入数据文件制作脚本。最好的方法是什么,如何处理这些论点?脚本的用法应该是:
./script.sh -a sth -b sth - c sth -d sth input1 input2 input3
我可以使用 getopts 处理参数和参数,但我不知道如何处理这些输入文件,因为它们没有标志。 谢谢
【问题讨论】:
while getopts ":a:b:c:d:" opt; do
case "$opt" in
a) i=$OPTARG ;;
b) j=$OPTARG ;;
c) k=$OPTARG ;;
d) l=$OPTARG ;;
esac
done
shift $(( OPTIND - 1 ))
for file in "$@"; do
# your stuff here
done
请试试这个,这可能会解决你的目的
我自己的评论促使我扩展答案:
如果您想仅通过 getopts 进行操作: 您必须将脚本称为
./script -a hj -b op -c zx -d some -f "File in list seperated with spaces"
while getopts ":a:b:c:d:f:" opt; do
case "$opt" in
a) i=$OPTARG ;;
b) j=$OPTARG ;;
c) k=$OPTARG ;;
d) l=$OPTARG ;;
f) files=$OPTARG ;;
esac
done
#no shift is required now, since we have file list in $files
for file in $files; do
# your stuff here
done
【讨论】:
for loop :)。解释部分:阅读转移 cmdline 参数(shift $(( OPTIND - 1 ))),您将了解$@ 如何只获得您想要的文件。
getopts 处理选项,将非可选参数留在$@ 中以供以后处理。
script -d some1 -f something -p "list of files" -j "list of files"这样的列表