티스토리 뷰
bash 에서 yaml 파일을 해석해서, 환경변수로 설정해주는 간단한 코드입니다.
예를 들어, setting.yaml 이라는 파일이 있을 때
default:
mysql:
host: localhost
port: 3306
username: test
redis:
host: localhost
port: 1122
test:
mysql:
host: remote.example.net
port: 3306
username: test
위와 같은 파일을 해석하고 싶을 때, 다음과 같은 방식으로 사용합니다.
#!/bin/bash
YAML=settings.yaml ENV=default source parse_yaml.sh
echo $mysql_host
echo $mysql_port
echo $mysql_username
최상위 객체를 ENV에 넘겨주면, 각 객체를 "_"로 연결하여 환경변수로 만들어 줍니다. 자세한 내용은 코드를 보시기 바랍니다. 끝!
$ cat parse_yaml.sh
# Copyright 2016 By Hojin Choi
# You should source this file as "YAML=../config/settings.yaml source parse_yaml.sh"
if test -z "YAML"; then
echo "YAML is not set"
exit 1
fi
if test -z "$LEADSPACE"; then
LEADSPACE=" "
fi
if test -z "$FIELDSP"; then
FIELDSP="_"
fi
if test -z "$ENV"; then
ENV="default"
fi
TMPSH="/tmp/tmp.$$.sh"
#Remove white space from IFS, we use only new line character
lastdepth="0"
while IFS="\n" read line
do
depth=`echo "$line" | sed -e "s;$LEADSPACE;@;g" | sed -r -e 's;^(@*).*;\\1;' | wc -c`
read k v <<<"$line"
k=$(echo $k| tr -d ':')
keys[$depth]="$k"
if test "$lastdepth" -ne "$depth"; then
lastdepth=$depth
fi
unset keys[$(($lastdepth+1))]
unset keys[$(($lastdepth+2))]
unset keys[$(($lastdepth+3))]
unset keys[$(($lastdepth+4))]
unset keys[$(($lastdepth+5))]
unset keys[$(($lastdepth+6))]
unset keys[$(($lastdepth+7))]
unset keys[$(($lastdepth+8))]
if test "$ENV" != "${keys[1]}"; then
continue
fi
if test -z "$v"; then
continue
fi
v=$(echo $v| tr -d '"')
read key <<<"$(echo ${keys[@]:2} | tr ' ' $FIELDSP)"
echo $key=$v
done < "$YAML" > "$TMPSH"
. "$TMPSH"
rm -f "$TMPSH"
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 디버깅
- perl
- OpenID
- url
- 식물
- 대화
- ssh
- nodejs
- 커피
- Tattertools plugin
- macosx
- 퀴즈
- VIM
- BlogAPI
- writely
- 킹벤자민
- SVN
- tattertools
- 벤자민
- 수선화
- 오픈소스
- Subversion
- 덴드롱
- TCP/IP
- MySQL
- 구근
- SSO
- JavaScript
- Linux
- 클레로덴드럼
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함