Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a bash function, say foo ()

I pass some parameters in a string like user=user1 pass=pwd address=addr1 other= Parameters may be missed or passed with random sequence I need to assign appropriate values inside the foo

USER=...
PASSWORD=...
ADDRESS=...

How can I do it?

I can use grep multiple times, but this way is not good, eg

foo ()
{
  #for USER
  for par in $* ; do 
    USER=`echo $par | grep '^user='` 
    USER=${USER#*=} 
  done
  #for PASSWORD
  for ...
}
share|improve this question

1 Answer 1

up vote 0 down vote accepted

Is this what you mean?

#!/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

Result:

$ sh test.sh username password address not a data
username password address

Your question is also already answered here:

Passing parameters to a bash function


Apparently the above answer isn't related to the question, so how about this?

#!/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

Result:

$ sh test.sh
username = user
password = passwd
other =
another = what?
share|improve this answer
    
Not completelly, the set of parameters is not strictly sequnsed. I can pass address=addr1 pass=pwd user=user1 other= or just miss some of parameters. So USER may be $1 or $2 or another –  Torrius May 16 '13 at 9:13
    
My bad. but you should add those details to your question –  ardiyu07 May 16 '13 at 9:23
    
I editted my answer –  ardiyu07 May 16 '13 at 9:47
    
Thanks, this good! But I did use own solution. FYI params=`echo $* | tr " " "\n"` ; USER=`echo $params | grep ^user=` ; USER=${USER#*=} ; PASSWORD=`echo $params | grep ^pass=` ; PASSWORD=${PASSWORD#*=}` –  Torrius May 16 '13 at 14:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.