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 ...
}
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?