我有一个应用程序数组,初始化如下:
depends=$(cat ~/Depends.txt)
Run Code Online (Sandbox Code Playgroud)
当我尝试解析列表并使用时将其复制到新数组中,
for i in "${depends[@]}"; do
if [ $i #isn't installed ]; then
newDepends+=("$i")
fi
done
Run Code Online (Sandbox Code Playgroud)
会发生什么是只有依赖的第一个元素依赖于newDepends.
for i in "${newDepends[@]}"; do
echo $i
done
Run Code Online (Sandbox Code Playgroud)
^^这只会产生一件事.所以我想弄清楚为什么我的for循环只是移动第一个元素.整个列表原本依赖,所以不是这样,但我完全没有想法.
use*_*530 103
a=(foo bar "foo 1" "bar two") #create an array
b=("${a[@]}") #copy the array in another one
for value in "${b[@]}" ; do #print the new array
echo "$value"
done
Run Code Online (Sandbox Code Playgroud)
nii*_*ani 21
在bash中复制非关联数组的最简单方法是:
arrayClone=("${oldArray[@]}")
或者将元素添加到预先存在的数组:
someArray+=("${oldArray[@]}")
将保留元素中的换行符/空格/ IFS.
对于复制关联数组,Isaac的解决方案非常有用.
小智 5
其他答案中给出的解决方案不适用于关联数组,也不适用于具有非连续索引的数组.这是一个更通用的解决方案:
declare -A arr=([this]=hello [\'that\']=world [theother]='and "goodbye"!')
temp=$(declare -p arr)
eval "${temp/arr=/newarr=}"
diff <(echo "$temp") <(declare -p newarr | sed 's/newarr=/arr=/')
# no output
Run Code Online (Sandbox Code Playgroud)
而另一个:
declare -A arr=([this]=hello [\'that\']=world [theother]='and "goodbye"!')
declare -A newarr
for idx in "${!arr[@]}"; do
newarr[$idx]=${arr[$idx]}
done
diff <(echo "$temp") <(declare -p newarr | sed 's/newarr=/arr=/')
# no output
Run Code Online (Sandbox Code Playgroud)
您可以通过指定索引将第一个数组的元素插入到副本中来复制数组:
#!/bin/bash
array=( One Two Three Go! );
array_copy( );
let j=0;
for (( i=0; i<${#array[@]}; i++)
do
if [[ $i -ne 1 ]]; then # change the test here to your 'isn't installed' test
array_copy[$j]="${array[$i]}
let i+=1;
fi
done
for k in "${array_copy[@]}"; do
echo $k
done
Run Code Online (Sandbox Code Playgroud)
其输出将是:
One
Three
Go!
Run Code Online (Sandbox Code Playgroud)
关于 bash 数组的有用文档位于TLDP上。