问题
Hi I am having an array and want to add strings that contain spaces. How can this be done? the following example code shows what I want to do:
#!/bin/bash
# works on BASH versions >4
ShowArray1() {
echo "in ShowArray1 -----------------------"
declare -n AlocalArray="$1"
declare -p AlocalArray
echo "Showing content of array"
local iMax=${#AlocalArray[@]}
echo "ARRAYCOUNT: $iMax"
for ((iItem=0; iItem < iMax ; iItem++)); do
echo "ITEM: ${AlocalArray[$iItem]}"
done
}
declare -a AARRAY
#declare -p AARRAY
iMax=${#AARRAY[@]}
echo "HERE ARRAYCOUNT: $iMax ITEMS in ARRAY"
ShowArray1 "AARRAY"
sParam="1st Item"
AARRAY+=($sParam)
ShowArray1 "AARRAY"
Problem is that the Item "1st Item" is added as two elements into the array. Output:
Showing content of array
ARRAYCOUNT: 2
ITEM: 1st
ITEM: Item
回答1:
Double quote the variable to prevent the expansion:
AARRAY+=("$sParam")
来源:https://stackoverflow.com/questions/29015565/bash-adding-a-string-with-a-space-to-an-array-adds-two-elements