bash study - array

array 정의

변수 정의시 괄호를 쓰면 array로 정의된다. 대괄호에는 Index를 쓰면 해당 Index에 정의된 값을 호출할 수 있다.

#!/bin/bash
arr=(Hello World)
echo ${arr[0]} ${arr[1]}


array에서 !, #, * 의 용도

  • array[*] : 배열의 모든 item을 의미한다.
  • !array[*] : 배열의 모든 index를 의미한다.
  • #array[*] : 배열의 element 수를 의미한다.
  • #array[0] : 배열의 첫번째 element의 길이를 의미한다.

아래는 예시

#!/bin/bash
arr=(Hello World This is Array)

echo 'Print all the items :' ${arr[*]}        
echo 'Print all the idexes : '${!arr[*]}       
echo 'Print the number of the items :' ${#arr[*]}
echo 'Print length of item 0 : ' ${#arr[0]}


결과

Print all the items : Hello World This is Array
Print all the idexes : 0 1 2 3 4
Print the number of the items : 5
Print length of item 0 :  5


*와 @의 차이

*와 @ 둘다 '모두'를 의미한다.
"${arr[*]}"는 모든 요소들을 하나의 단어로 인식하고
"${arr[@]}"는 각 요소들을 구분해서 인식한다
아래를 따옴표가 있을때와 없을때, *를 썼을때와 @를 썼을때 차이를 보려고 테스트 한 내용

각 배열에 저장된 element의 수 확인

arr=("Hello World" "This is Array")

at_quote=("${arr[@]}")
at_unquote=(${arr[@]})
as_quote=("${arr[*]}")
as_unquote=(${arr[*]})

echo "Number of elements in arr : ${#arr[*]}"
echo "Number of elements in (\"\${arr[@]}\") : ${#at_quote[*]}"
echo "Number of elements in (\${arr[@]}) : ${#at_unquote[*]}"
echo "Number of elements in (\"\${arr[*]}\") : ${#as_quote[*]}"
echo "Number of elements in (\${arr[*]}) : ${#as_unquote[*]}"


결과

Number of elements in arr : 2
Number of elements in ("${arr[@]}") : 2
Number of elements in (${arr[@]}) : 5
Number of elements in ("${arr[*]}") : 1
Number of elements in (${arr[*]}) : 5


각 배열에 저장된 element 들 확인

#!/bin/bash
arr=("Hello World" "This is Array")

at_quote=("${arr[@]}")
at_unquote=(${arr[@]})
as_quote=("${arr[*]}")
as_unquote=(${arr[*]})

echo "at_quote"
for i in ${!at_quote[*]}
do
printf "    %s\n" "${at_quote[$i]}"
done

echo "at_unquote"
for i in ${!at_unquote[*]}
do
printf "    %s\n" "${at_unquote[$i]}"
done

echo "as_quote"
for i in ${!as_quote[*]}
do
printf "    %s\n" "${as_quote[$i]}"
done

echo "as_unquote"
for i in ${!as_unquote[*]}
do
printf "    %s\n" "${as_unquote[$i]}"
done


결과

at_quote
    Hello World
    This is Array
at_unquote
    Hello
    World
    This
    is
    Array
as_quote
    Hello World This is Array
as_unquote
    Hello
    World
    This
    is
    Array


활용 : array에서 홀수 index 값들을 출력하기

array=(a b c d e f g h)
    for (( i=0; i<${#array[@]}; i+=2 )); do
        printf "${array[i]}\n"
    done


결과
a
c
e
g

댓글 쓰기

0 댓글