解析shell脚本参数

时间:2011-02-03 03:21:03

标签: linux bash shell unix

$myscript.sh -host blah -user blah -pass blah

我想将参数传递给它。

我习惯做$1$2$3 ....但我想开始命名

5 个答案:

答案 0 :(得分:15)

有很多方法可以解析sh中的参数。 Getopt很好。这是一个简单的脚本,可以手工解析:

#!/bin/sh
# WARNING: see discussion and caveats below
# this is extremely fragile and insecure

while echo $1 | grep -q ^-; do
    # Evaluating a user entered string!
    # Red flags!!!  Don't do this
    eval $( echo $1 | sed 's/^-//' )=$2
    shift
    shift
done

echo host = $host
echo user = $user
echo pass = $pass
echo args = $@

示例运行如下:

$ ./a.sh -host foo -user me -pass secret some args
host = foo
user = me
pass = secret
args = some args

请注意,这甚至不具备远程可靠性,并且对安全性非常开放 因为脚本eval是用户构造的字符串。它只是 意味着作为一种可能的做事方式的例子。一种更简单的方法是要求用户在环境中传递数据。在一个bourne shell中(即任何不在csh系列中的东西):

$ host=blah user=blah pass=blah myscript.sh

效果很好,变量$host$user$pass将在脚本中提供。

#!/bin/sh
echo host = ${host:?host empty or unset}
echo user = ${user?user not set}
...

答案 1 :(得分:9)

答案 2 :(得分:7)

这是一种处理长期和短期期权的简单方法:

while [[ $1 == -* ]]; do
    case "$1" in
      -h|--help|-\?) show_help; exit 0;;
      -v|--verbose) verbose=1; shift;;
      -f) if (($# > 1)); then
            output_file=$2; shift 2
          else 
            echo "-f requires an argument" 1>&2
            exit 1
          fi ;;
      --) shift; break;;
      -*) echo "invalid option: $1" 1>&2; show_help; exit 1;;
    esac
done

来自How can I handle command-line arguments (options) to my script easily?

答案 3 :(得分:0)

我采用上面的William Pursell示例(使用Dennis Williamson的建议)来获取此格式的参数: script -param1 = value1 -param2 = value2 ...

以下是带有单行参数解析器的代码(将其保存在文件'脚本')中:

#!/bin/bash

while echo $1 | grep ^- > /dev/null; do declare $( echo $1 | sed 's/-//g' | sed 's/=.*//g' | tr -d '\012')=$( echo $1 | sed 's/.*=//g' | tr -d '\012'); shift; done

echo host = $host
echo user = $user
echo pass = $pass

你这样称呼它:

script -host=aaa -user=bbb -pass=ccc

,结果是

host = aaa
user = bbb
pass = ccc

有人知道更短的代码来解析参数吗?

答案 4 :(得分:0)

这是我的方法:

class MyAdminViews(ModelView):
    def is_accessible(self):
        if current_user.is_authenticated:
            user = User.query.filter_by(role=current_user.role).first()
            res = user.role == "admin"
            return res