using bash to append a string to array
I have the following function that does not iterate through the array I want to be able to do some manipulation on each element in the array[@].
it appears the below array has only one item in the array whereas i want the array to have 3 items hence the loop three times printing the message Any ideas why this is not happening ??? function foo() { name =$1 array=( "$2" ) for i in `seq 0 $(( ${#array[@]} - 1 ))`; do echo "$i: ${array}" echo "./prog $name ${array}" done } NAME ="BLAH" arrayP+=("TEST") ; arrayP+=("TESTB") arrayP+=("TESTC") foo $NAME "${arrayP[@]}" |
Try echo "$i: ${array[i]}"
|
sorry that was a typo i was echo array[i]
Also the in the foo function i only get one element printed out $2 if i use $@ then i get $NAME and array elements I think this is problem . any ideas why $2 doesn't have all array elements ??? |
Code:
shouldBe() |
1) Please use [code][/code] tags around your code, to preserve formatting and to improve readability.
2) When setting a variable, you can't have any spaces around the equals sign. 3) Code:
array=( "$2" ) Exception: quoting "${array[@]}" will expand to each individual array element, with those elements being treated as if they were quoted separately. So when you call your function, you're not getting a $2, you're getting a "$2" "$3" "$4", et cetera. A better way to handle your function then would be like this: Code:
foo() { 4) $(..) is recommended over `..`, and seq isn't usually necessary when you have brace expansion, although it's not easy to use variables with them. A better way to iterate through the array elements though is to use this: Code:
for i in ${!array[@]}; do 5) Finally, why not simply set your arrayP like this? Code:
arrayP=( TEST TESTB TESTC ) Code:
arrayP=( TEST TEST{B..C} ) |
Quote:
|
All times are GMT -5. The time now is 02:38 PM. |