我怎么能创建这个小脚本?
例如:
~$ script.sh -b my small string... other things -a other string -c any other string ant etc
Run Code Online (Sandbox Code Playgroud)
我只想要字符串,每个都有一个模式.
-b
my small string... other things
-a
other string
-c
any other string ant etc
Run Code Online (Sandbox Code Playgroud)
有谁知道如何实现它?
谢谢
这是一个非常简单的命令行参数循环.命令行参数是$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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
请注意我是如何引用长参数的.
我不推荐它,但是如果你真的想在命令行中传递多个单词但是将它们视为单个参数,那么你需要一些更复杂的东西:
#!/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
Run Code Online (Sandbox Code Playgroud)
用法示例:
~$ 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
Run Code Online (Sandbox Code Playgroud)
但是,不建议使用此用法.它违背UNIX规范和约定来连接像这样的参数.
| 归档时间: |
|
| 查看次数: |
1190 次 |
| 最近记录: |