C.W.K.
Stream
Lesson 08 of 12 · published

배열

~10 min · arrays, indexed, associative

Level 0창 구경꾼
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Indexed array (bash, zsh)

files=("a.txt" "b.txt" "c.txt")
echo "${files[0]}"        # bash: a.txt / zsh: 빈 값 (아래 참조)
echo "${files[@]}"        # 모든 원소
echo "${#files[@]}"       # 개수: 3
files+=("d.txt")          # append
unset 'files[1]'           # b.txt 슬롯 제거

bash 배열 인덱스 0 부터, zsh 는 1 부터 (기본). zsh 에 setopt KSH_ARRAYS 면 bash 의미로 통일. 처음 만나면 다 헷갈려.

Iteration

for f in "${files[@]}"; do
  echo "$f"
done

# 인덱스도 함께
for i in "${!files[@]}"; do
  echo "$i: ${files[i]}"
done

Associative array (bash 4+, zsh)

declare -A user
user[name]="Pippa"
user[age]=24
for k in "${!user[@]}"; do
  echo "$k = ${user[$k]}"
done

macOS bash 3.2 는 associative array 없음. brew bash 5 / zsh 사용 / 또는 병렬 indexed array 로 fallback.

command 결과를 배열로

readarray -t lines < ~/.zshrc        # bash 4+
lines=("${(@f)$(< ~/.zshrc)}")             # zsh
files=(*.txt)                              # glob

Slicing

echo "${files[@]:1:2}"   # 인덱스 1 부터 2 개
echo "${files[@]: -1}"   # 마지막 원소 (공백 주의)

Code

실전 배열 흐름·bash
#!/usr/bin/env bash
set -euo pipefail
todos=()
while IFS= read -r line; do
  [[ "$line" =~ ^TODO ]] && todos+=("$line")
done < notes.md
echo "${#todos[@]} TODO lines"
printf '  - %s\n' "${todos[@]}"

External links

Exercise

bash 스크립트: arr=(a b c d). 네 가지로 출력: "${arr[@]}", "${arr[*]}", "${arr[1]}", "${#arr[@]}". 경계 차이 확인.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.