这是一个非常简单的命令行参数循环。命令行参数是$1
,$2
等,命令行参数的数量是$#
。在我们完成之后,shift
命令会丢弃这些参数。
#!/bin/bash
while [[ $# -gt 0 ]]; do
case "$1" in
-a) echo "option $1, argument: $2"; shift 2;;
-b) echo "option $1, argument: $2"; shift 2;;
-c) echo "option $1, argument: $2"; shift 2;;
-*) echo "unknown option: $1"; shift;;
*) echo "$1"; shift;;
esac
done
UNIX命令通常希望您自己引用多字参数,以便它们显示为单个参数。用法如下:
~$ script.sh -b 'my small string... other things' -a 'other string' -c 'any other string ant etc'
option -b, argument: my small string... other things
option -a, argument: other string
option -c, argument: any other string ant etc
请注意我是如何引用长参数的。
我不建议这样做,但如果你真的想在命令行多个单词通过,但把它们作为单一的参数,你需要的东西多一点复杂:
#!/bin/bash
while [[ $# -gt 0 ]]; do
case "$1" in
-a) echo "option: $1"; shift;;
-b) echo "option: $1"; shift;;
-c) echo "option: $1"; shift;;
-*) echo "unknown option: $1"; shift;;
*) # Concatenate arguments until we find the next `-x' option.
OTHER=()
while [[ $# -gt 0 && ! ($1 =~ ^-) ]]; do
OTHER+=("$1")
shift
done
echo "${OTHER[@]}"
esac
done
用法示例:
~$ script.sh -b my small string... other things -a other string -c any other string ant etc
option: -b
my small string... other things
option: -a
other string
option: -c
any other string ant etc
但是,再次强调这种用法是不被推荐的。它违背了UNIX规范和约定来连接这样的参数。
目前尚不清楚你想要什么。你是否想要将标志-a,-b和-c分开,并且在列表中分别拥有一组其他参数?另外,你是否正在寻找一种不使用引号或多个单词参数的方法? – Slartibartfast 2010-06-24 02:12:39
我想要的是,每当有一个参数(-a或-b或其他)时,脚本在此之后捕获所有字符串,并将其放入一个变量中,我还需要检查带有大小写或其他模式的参数。我知道如何使这只有一个参数,但具有多个参数?谢谢。 – fixo2020 2010-06-24 03:05:43