Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

bash array passing args

Status
Not open for further replies.

uuperl

Programmer
Feb 20, 2006
33
US
Hi, I have question about the following script. If I define the variable in the script, then the output came out correct. My question is if I passing FOO and BAR as args through script, then the output is wrong.

How can I passing correct through args through script?

thanks!

#!/bin/sh
#FOO=( bar string 'some text' )
#BAR=( foo string 'other text' )

FOO=( $1 )
BAR=( $2 )
foonum=${#FOO}

for ((i=0;i<$foonum;i++)); do
echo ${FOO[${i}]} ${BAR[${i}]}
done
 
How about this?
Code:
#!/bin/bash
#FOO=( bar string 'some text' )
#BAR=( foo string 'other text' )

FOO="$1"
BAR="$2"
foonum=${#FOO}

for ((i=0;i<$foonum;i++)); do
        echo ${FOO[${i}]} ${BAR[${i}]}
done
If not, show us some sample input and the wrong output. It's not clear what you are expecting it to do.

 
Here is my issue:

When I define the FOO and BAR variable inside the script, then the output will be correct like the following:

bar foo
string string
some text other text

When I passing the variable FOO and BAR through script, then the output will not work

$ ./test "bar string 'some text'" "foo string 'other text'"

output like following:
bar bar string 'some text' foo string 'other text'

which is not what I want like above first output.

thanks!
 
Then my example should work. The quotes around $1 and $2 should protect the variable. It has spaces in the value you are passing, so they need to be quoted to keep it looking like one value to the shell.

 
The var=(one two three) syntax you are using is a Bash-specific feature, so you should make it clear by using #!/bin/bash at the beginning of your script.

This seems to fix your problem:

Code:
eval FOO=($1)
eval BAR=($2)

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top