2013-05-16 134 views
0

我有一個bash的功能,說foo()解析bash函數參數

我傳遞一些參數,像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

這是什麼意思?

#!/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? 
+0

不completelly,設定的參數不嚴格sequnsed。我可以傳遞'address = addr1 pass = pwd user = user1 other ='或者只是錯過了一些參數。所以USER可能是$ 1或$ 2或者其他 – Torrius

+0

我的不好。但你應該添加這些細節到你的問題 – ardiyu07

+0

我編輯我的答案 – ardiyu07