数组声明

数组声明

如何在 Ubuntu 中声明数组?我尝试了以下代码

Unix=('Zero' 'One' 'Two')

#echo -n "area2[0] = "
echo ${area2[@]}
# Aha, zero-based indexing (first element of array is [0], not [1]).

#echo -n "area2[1] = "
#echo $ {area2[1]}  

这在 Ubuntu 中不起作用。

答案1

如果你调用/命名了你的数组Unix,为什么要使用area2?!? 或者你在此数组之前声明过命名吗area2?试试这个:

Unix=('Zero' 'One' 'Two')

echo "Unix = ${Unix[@]}"
echo "Unix[0] = ${Unix[0]}"
echo "Unix[1] = ${Unix[1]}"

请阅读一些有关Bash 中的数组

答案2

我将给你一个完整的例子:

#!/bin/bash    
array=("first item" "second item" "third" "item")

echo "Number of items in original array: ${#array[*]}" 

for ix in ${!array[*]} 
do
    printf "   %s\n" "${array[$ix]}" 
done 

arr=(${array[*]}) 
echo "After unquoted expansion: ${#arr[*]}" 

for ix in ${!arr[*]} 
do
    printf "   %s\n" "${arr[$ix]}" 
done 

arr=("${array[*]}") 
echo "After * quoted expansion: ${#arr[*]}" 

for ix in ${!arr[*]} 
do
    printf "   %s\n" "${arr[$ix]}" 
done 

arr=("${array[@]}") 
echo "After @ quoted expansion: ${#arr[*]}" 

for ix in ${!arr[*]}     
do
    printf "   %s\n" "${arr[$ix]}" 
done

我希望它有帮助。

相关内容