Shell Script: bash 기본과 실전 패턴
Shell Pipeline, shell-pipeline, Shell Script, bash script, 쉘 스크립트, shell scripting
정의
Shell Script 는 shell (bash, zsh, sh) 커맨드를 파일로 저장하여 자동화하는 스크립트. DevOps, CI/CD, sysadmin 필수.
안전한 시작
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
-e: 명령 실패 시 즉시 종료-u: 정의 안 된 변수 참조 시 오류-o pipefail: pipe 안의 실패도 캐치- IFS: 안전한 word splitting
변수
name="Alice"
echo "Hello, $name"
echo "Hello, ${name}"
# 기본값
echo "${port:-8080}" # $port 없으면 8080
# 필수
echo "${API_KEY:?required}" # 없으면 error message
# 배열
arr=(a b c)
echo "${arr[0]}"
echo "${arr[@]}"
조건과 반복
if [[ -f "$file" ]]; then
echo "exists"
fi
if [[ "$env" == "prod" ]]; then
...
elif [[ "$env" == "dev" ]]; then
...
fi
for f in *.log; do
echo "$f"
done
while read -r line; do
echo "$line"
done < input.txt
함수
greet() {
local name="$1"
echo "Hello, $name"
}
greet "World"
에러 처리
trap 'cleanup' EXIT ERR INT TERM
cleanup() {
rm -f "$temp_file"
}
# 특정 명령 실패 허용
some_command || true
실전 패턴
stdin/stdout 처리
cat file.txt | grep pattern | wc -l
grep pattern < file.txt
grep pattern file.txt > out.txt 2>&1
인자 파싱
while getopts "hi:o:" opt; do
case $opt in
h) echo "usage: ..." ;;
i) input="$OPTARG" ;;
o) output="$OPTARG" ;;
*) exit 1 ;;
esac
done
함정
- quoting:
$var는 항상"$var"(공백 처리) - [ vs [[: bash 는
[[가 안전 (short-circuit, no word splitting) - **backtick vs ( )` 가 nesting 가능
- subshell:
( )안 변경은 밖에 반영 안 됨
💬 댓글