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]}"
doneAssociative array (bash 4+, zsh)
declare -A user
user[name]="Pippa"
user[age]=24
for k in "${!user[@]}"; do
echo "$k = ${user[$k]}"
donemacOS 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) # globSlicing
echo "${files[@]:1:2}" # 인덱스 1 부터 2 개
echo "${files[@]: -1}" # 마지막 원소 (공백 주의)