乐趣区

Linux-Shell-Array

Array Operation

Basic

# Initial
arr=(Hello World)

# Print
echo ${arr[0]} ${arr[1]}

# Assign
arr[0]=Hello
arr[1]=World

# Append
# Notice: arr+="Hello" is wrong
arr+=("Hello")
arr+=("World")

Iteration

${arr[*]}  # All of the items in the array  
${!arr[*]}  # All of the indexes in the array  
${#arr[*]}  # Number of items in the array  
${#arr[0]}  # Length of item zero  

Basic Examples

#!/bin/bash
array=(one two three four [5]=five)

echo "Array size: ${#array[*]}"

# --------
# Array size: 5
# --------

echo "Array items:"
for item in ${array[*]}
do
    printf "%s\n" $item
done

# --------
# Array items:
#    one
#    two
#    three
#    four
#    five
# --------

echo "Array indexes:"
for index in ${!array[*]}
do
    printf "%d\n" $index
done

# --------
# Array indexes:
#    0
#    1
#    2
#    3
#    5
# --------

echo "Array items and indexes:"
for index in ${!array[*]}
do
    printf "%4d: %s\n" $index ${array[$index]}
done

# --------
# Array items and indexes:
#    0: one
#    1: two
#    2: three
#    3: four
#    5: five
# --------

Advanced Examples

#!/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
echo

# --------
# Number of items in original array: 4
#    first item
#    second item
#    third
#    item
# --------

arr=(${array[*]})
echo "After unquoted expansion: ${#arr[*]}"
for ix in ${!arr[*]}
do
    printf "%s\n" "${arr[$ix]}"
done
echo

# --------
# After unquoted expansion: 6
#    first
#    item
#    second
#    item
#    third
#    item
# --------

arr=("${array[*]}")
echo "After * quoted expansion: ${#arr[*]}"
for ix in ${!arr[*]}
do
    printf "%s\n" "${arr[$ix]}"
done
echo

# --------
# After * quoted expansion: 1
#    first item second item third item
# --------

arr=("${array[@]}")
echo "After @ quoted expansion: ${#arr[*]}"
for ix in ${!arr[*]}
do
    printf "%s\n" "${arr[$ix]}"
done

# --------
# After @ quoted expansion: 4
#    first item
#    second item
#    third
#    item
# --------
退出移动版