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}
...