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

스크립트의 함수

~10 min · function, local, return

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

모양

greet() {
  local name="${1:?name required}"
  echo "hi, $name"
}
greet Pippa

함수는 스크립트처럼 positional arg 받음 ($1, $2, $@, $#). 함수 변수는 항상 local — 안 하면 caller scope 로 leak.

반환 값

return N 가 caller 의 $? 설정. N 은 0–255. 문자열 반환은 echo + $( ) 캡처:

upper() { echo "${1^^}"; }   # bash 4+
name="$(upper hello)"

scope 함정

# Bug — caller 로 tmp leak
f() { tmp=42; echo $tmp; }
tmp=hello
f         # 42
echo $tmp  # 42 (hello 가 아님!)

# Fix
f() { local tmp=42; echo $tmp; }

함수 export

기본적으로 shell 에 정의한 함수는 자식 프로세스에게 안 보임. export -f myfunc 로 bash subshell 에 노출 (zsh 는 다름). 대부분 스크립트는 불필요.

라이브러리 스크립트

helper 를 lib.sh 에 모으고 source ./lib.sh (또는 . ./lib.sh) 로 로드. 함수가 호출 shell 에서 사용 가능. 흔한 패턴: 최상위 entry 스크립트 + 여러 라이브러리 파일을 시작에 한 번 source.

Code

lib.sh + entry 패턴·bash
# lib.sh
log()  { printf '%(%H:%M:%S)T %s\n' -1 "$*" >&2; }
die()  { log "FATAL: $*"; exit 1; }

# entry.sh
#!/usr/bin/env bash
set -euo pipefail
source "$(dirname "$0")/lib.sh"
log 'starting'
[[ $# -eq 1 ]] || die 'usage: entry <name>'

External links

Exercise

lib.shlog, die helper 작성. 작은 스크립트에서 source. 함수 안에 local 변수 추가하고 함수 반환 후 같은 이름이 leak 안 됐는지 확인.

Progress

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

댓글 0

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

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