有人可以帮我解释临时变量的差异,因为我正在向数组中添加元素吗?
#!/bin/bash
declare -a finaldirs1
declare -a finaldirs2
declare -a files=("Planes" "Trains" "Automobiles")
echo "A)..................................."
for el1 in "${files[@]}"; do
tmpe=$(printf "1:%s." "${el1}")
finaldirs1+=($tmpe)
done
for elA in "${finaldirs1[@]}"; do
echo "First: " $elA
done
echo "B)..................................."
for el2 in "${files[@]}"; do
finaldirs2+=$(printf "2:%s." "${el2}")
done
for elB in "${finaldirs2[@]}"; do
echo "Second: " $elB
done
echo "DONE................................."
简而言之,第二个版本以某种方式将所有元素组合在一起。输出:
A)...................................
First: 1:Planes.
First: 1:Trains.
First: 1:Automobiles.
B)...................................
Second: 2:Planes.2:Trains.2:Automobiles.
DONE.................................
答案 0 :(得分:2)
finaldirs2+=$(printf "2:%s." "${el2}")
应该是
finaldirs2+=($(printf "2:%s." "${el2}"))
答案 1 :(得分:2)
你错过了几个括号。
#!/bin/bash
declare -a finaldirs1
declare -a finaldirs2
declare -a files=("Planes" "Trains" "Automobiles")
echo "A)..................................."
for el1 in "${files[@]}"; do
tmpe=$(printf "1:%s." "${el1}")
finaldirs1+=($tmpe)
done
for elA in "${finaldirs1[@]}"; do
echo "First: " $elA
done
echo "B)..................................."
for el2 in "${files[@]}"; do
finaldirs2+=($(printf "2:%s." "${el2}"))
done
for elB in "${finaldirs2[@]}"; do
echo "Second: " $elB
done
echo "DONE................................."
您可以看到,附加到数组时它就像arr+=('element')
一样,而arr+='element'
只会附加到字符串arr
。