Linux Array & Associative Array

Ordinary Array:

Assign1: arrayName=(value1 value2 ...)

Assign2: arrayName[index]=value

Length: ${#arrayName[*]} or ${#arrayName[@]} 

Indexes: ${!arrayName[*]} or ${#arrayName[@]}

Example:

#!/bin/bash

group1=(rio amos)
group2[0]=bill
group2[1]=frank
group2[2]=bruce

echo group1 has ${#group1[*]} person[s]
echo they are ${group1[*]}
echo group2 has ${#group2[@]} person[s]
echo they are ${group2[@]}

Associative Array:

Define: declare -A arrayName

Assign1: arrayName=([index1]=value1 [index2]=value2 ...)

Assign2: arrayName[index]=value

Length: ${#arrayName[*]} or ${#arrayName[@]}

Indexes: ${!arrayName[*]} or ${#arrayName[@]}

Example:

#!/bin/bash

declare -A team1
declare -A team2

team1=([rio]=1981 [amos]=1990)
team2[frank]=1983
team2[bill]=1984
team2[bruce]=1990

echo team1 has ${#team1[*]} person[s]
echo they are ${!team1[*]}

echo team2 has ${#team2[@]} person[s]
echo they are ${!team2[@]}



你可能感兴趣的:(linux,shell,array)