There are lots of ways to parse arguments in sh. Getopt is good. Here's a simple script that parses things by hand:
#!/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 sample run looks like:
$ ./a.sh -host foo -user me -pass secret some args
host = foo
user = me
pass = secret
args = some args
Note that this is not even remotely robust and massively open to security
holes since the script eval's a string constructed by the user. It is merely
meant to serve as an example for one possible way to do things. A simpler method is to require the user to pass the data in the environment. In a bourne shell (ie, anything that is not in the csh family):
$ host=blah user=blah pass=blah myscript.sh
works nicely, and the variables $host
, $user
, $pass
will be available in the script.
#!/bin/sh
echo host = ${host:?host empty or unset}
echo user = ${user?user not set}
...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…