我有一个bash函数,比如foo ()
我在user=user1 pass=pwd address=addr1 other=
这样的字符串中传递了一些参数
参数可能会被遗漏或以随机序列传递
我需要在foo
USER=...
PASSWORD=...
ADDRESS=...
我该怎么做?
我可以多次使用grep
,但这种方式并不好,例如
foo ()
{
#for USER
for par in $* ; do
USER=`echo $par | grep '^user='`
USER=${USER#*=}
done
#for PASSWORD
for ...
}
答案 0 :(得分:0)
这是你的意思吗?
#!/bin/sh
# usage: sh tes.sh username password addr
# Define foo
# [0]foo [1]user [2]passwd [3]addr
foo () {
user=$1
passwd=$2
addr=$3
echo ${user} ${passwd} ${addr}
}
# Call foo
foo $1 $2 $3
结果:
$ sh test.sh username password address not a data
username password address
您的问题也已在此处得到解答:
Passing parameters to a Bash function
显然上述答案与问题无关, 那怎么样?
#!/bin/sh
IN="user=user pass=passwd other= another=what?"
arr=$(echo $IN | tr " " "\n")
for x in $arr
do
IFS==
set $x
[ $1 = "another" ] && echo "another = ${2}"
[ $1 = "pass" ] && echo "password = ${2}"
[ $1 = "other" ] && echo "other = ${2}"
[ $1 = "user" ] && echo "username = ${2}"
done
结果:
$ sh test.sh
username = user
password = passwd
other =
another = what?