bash adding a string with a space to an array adds two elements

拟墨画扇 提交于 2019-12-13 01:11:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!