0

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 ...
}
Torrius
  • 737
  • 3
  • 12
  • 20

1 Answers1

0

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?
Community
  • 1
  • 1
ardiyu07
  • 1,790
  • 2
  • 17
  • 29
  • 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 09:13
  • My bad. but you should add those details to your question – ardiyu07 May 16 '13 at 09:23
  • 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