庆典添加一个字符串到一个数组的空间增加了两个元素 [英] bash adding a string with a space to an array adds two elements
本文介绍了庆典添加一个字符串到一个数组的空间增加了两个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,要添加包含空格的字符串。如何才能做到这一点?
下面的例子code显示了我想做的事:
#!/斌/庆典#适用于BASH版本→4
ShowArray1(){
回声中ShowArray1 -----------------------
声明-n AlocalArray =$ 1
声明-p AlocalArray
回声显示阵列的内容 当地IMAX = $ {#AlocalArray [@]}
回声ARRAYCOUNT:$ IMAX
对((的iItem = 0;&的iItem LT; IMAX;的iItem ++));做
回声项目:$ {AlocalArray [$的iItem]}
DONE
}声明-a AARRAY
#declare -p AARRAY
IMAX = $ {#AARRAY [@]}
回声HERE ARRAYCOUNT:$ IMAX在数组项ShowArray1AARRAY
sParam =1项
AARRAY + =($ sParam)ShowArray1AARRAY
问题是,该项目第1项添加为两个元素到阵列。输出:
数组的展示内容
ARRAYCOUNT:2
ITEM:1
项目:项目
解决方案
双引号的变量prevent扩展:
AARRAY + =($ sParam)
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
解决方案
Double quote the variable to prevent the expansion:
AARRAY+=("$sParam")
这篇关于庆典添加一个字符串到一个数组的空间增加了两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文