리눅스 > 쉘스크립트 > 배열(Array)

Redjini WiKi
< linux‎ | script(linux/script/배열에서 넘어옴)


배열 선언

array_name_1=("value 1" "value 2" "value 3")
array_name_2=(1 2 3)

배열 참조

array_name=("value 1" "value 2" "value 3")
 
echo "array_name[0]     = ${array_name[0]}"  #print array_name[0]
echo "array_name[2]     = ${array_name[2]}"  #print array_name[2]
echo "array_name[*]     = ${array_name[*]}"  #print array_name all item
echo "array_name[@]     = ${array_name[@]}"  #print array_name all item
echo "array_name index  = ${!array_name[@]}" #print array_name index number
echo "array_name size   = ${#array_name[@]}" #print array_name size
echo "array_name[0] size= ${#array_name[0]}" #print array_name[0] size

#출력 결과
#array_name[0]     = value 1
#array_name[2]     = value 3
#array_name[*]     = value 1 value 2 value 3
#array_name[@]     = value 1 value 2 value 3
#array_name index  = 0 1 2
#array_name size   = 3
#array_name[0] size= 7

배열 크기

array_name_1=("value 1" "value 2" "value 3")
 
echo ${#array_name_1[@]}  #print "3"

배열 출력

array_name=("value 1" "value 2" "value 3")
 
echo "array = ${array_name[@]}"
# 출력 결과
# array = value 1 value 2 value 3
 
printf "value = %s\n" "${array_name[@]}"
# 출력 결과
# value = value 1
# value = value 2
# value = value 3
 
for value in "${array_name[@]}"; do
    echo $value
done
# 출력 결과
# value 1
# value 2
# value 3
 
for (( i = 0 ; i < ${#array_name[@]} ; i++ )) ; do
    echo "value[$i] = ${array_name[$i]}"
done
# 출력 결과
# value[0] = value 1
# value[1] = value 2
# value[2] = value 3
 
for index in ${!array_name[*]} ; do
    printf "%4d: %s\n" "$index" "${array_name[$index]}"
done
# 출력 결과
#   0: value 1
#   1: value 2
#   2: value 3