base_role/overlay/Linux/usr/local/bin/yaml_to_bash2.bash
embed@git.macaw.me b50fd16591 first
2024-01-06 01:38:28 +00:00

35 lines
1.1 KiB
Bash
Executable File

#!/bin/sh
# -*- mode: sh; tab-width: 8; coding: utf-8-unix -*-
# pkuczynski/parse_yaml.sh
prog=$( basename $0 .bash )
ROLE=base
# FixMe: lists should be space delineated not comma
# Read YAML file from Bash script
# Credits: https://gist.github.com/pkuczynski/8665367
# Updated to support single quotes
parse_yaml() {
local prefix
local depth
local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
[ "$#" -gt 1 ] && prefix=$2 || prefix=""
[ "$#" -gt 2 ] && depth=$3 || depth=""
sed -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" \
-ne "s|^\($s\)\($w\)$s:$s'\(.*\)'$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" $1 |
awk -F$fs '{
indent = length($1)/2;
vname[indent] = $2;
for (i in vname) {if (i > indent) {delete vname[i]}}
if (length($3) > 0) {
vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("'$depth'")}
printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3);
}
}'
}
if [ -x /usr/bin/basename ] && [ $( basename -- $0 ) = 'yaml_to_bash2.bash' -o $( basename -- $0 ) = 'parse_yaml2.sh' ] ; then
parse_yaml "$@"
fi