2014-10-07 86 views
0

所有解析参数

我想写一个shell脚本(可以称之为mysh)这就要求另一个shell脚本(允许其命名由来)。

起源脚本需要几个参数的语法如下:

./origin.sh /A=appname,/U=admin,/LL=ADMINISTRATOR

在mysh脚本,起源脚本将被调用,可能有人请让我知道如何分析这些参数(/ A ,/ U,/ LL)在shell脚本中?通过定义变量?

这应该是一个容易的事,请大家仔细考虑一个简单的方法:d

感谢所有

+0

所以mysh.sh是一个shell脚本,你想用appname,admin和管理员参数执行origin.sh? 为什么写的语法像/ A = appname? – Travis 2014-10-07 00:41:33

+0

因为你在linux/unix上这样做,有没有一个很好的理由你为什么不使用linux/unix风格的选项,可以很容易地用'bash'解析? – John1024 2014-10-07 01:01:29

+0

你的脚本,*调用*'origin.sh',试图将参数解析为'origin.sh'?为什么?无论如何,你是不是只需要将它们交给'origin.sh'呢? – 2014-10-07 02:19:44

回答

0

改变“/”到“ - ”和“”空间,你可以使用getopts来解析和提取参数。在这里看到的例子:

http://wiki.bash-hackers.org/howto/getopts_tutorial

另外,摆脱了“/”和改变“”换空间,那么每个参数则是PARAM =值,这样你就可以起诉‘EVAL’设置这些是环境变量。

是这样的:

for P in $* 
do 
    eval $P 
done 
+0

只是为了P; do'会默认迭代'“$ @”'。 '$ *'是错误的 - 在IFS上发生分裂并扩展球 - 除非您确切知道*为什么您使用'$ *'而不是'“$ @”',否则不要使用它。 – 2014-10-07 01:07:04

+1

另请参阅http://mywiki.wooledge.org/BashFAQ/048 re:eval的安全问题。 – 2014-10-07 01:14:18

0

以下的代码解析成关联数组:

declare -A settings=() 

for arg; do        # iterate over all arguments 
    if [[ $arg = /* ]]; then    # ignore ones not starting with slashes 
    IFS=, read -r -a items <<<"$arg"  # split them out by commas... 
    for item in "${items[@]}"; do   # ...iterate over what we got by splitting 
     if [[ $item = *=* ]]; then   # ...ignore entries that don't have an = 
     settings[${item%%=*}]=${item#*=} # ...the part before the first = is the key 
              # and the rest is the value. 
     fi 
    done 
    fi 
done 

这可以被读出如下:

echo "App name is ${settings[A]}. User is ${settings[U]}."