전체/장난하기
parse yaml in bash
Coolen
2016. 4. 10. 14:59
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"
반응형