Last active
September 24, 2022 13:57
-
-
Save mabe-at/befb55910c6892789128 to your computer and use it in GitHub Desktop.
Parse YAML into shell variables using shyaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
name: 'Max Mustermann' | |
database: | |
host: 'localhost' | |
database: 'mydb' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
export PYTHONIOENCODING="utf_8" | |
parse_yaml() { | |
cat "$1" | shyaml keys | | |
while read -r key; do | |
local t | |
t=$(cat "$1" | shyaml get-type "$key") | |
case "$t" in | |
struct) | |
parse_struct "$1" "$2" "$key" | |
;; | |
sequence) | |
;; | |
*) | |
set_val "$1" "$2" "$key" | |
;; | |
esac | |
done | |
} | |
parse_struct() { | |
cat "$1" | shyaml keys "$3" | | |
while read -r key; do | |
local t | |
t=$(cat "$1" | shyaml get-type "$3.$key") | |
case "$t" in | |
struct) | |
parse_struct "$1" "$2" "$3.$key" | |
;; | |
sequence) | |
;; | |
*) | |
set_val "$1" "$2" "$3.$key" | |
;; | |
esac | |
done | |
} | |
set_val() { | |
local var | |
var=$(echo "$2_$3" | sed -e "s/\./_/g") | |
local val | |
val=$(cat "$1" | shyaml get-value "$3") | |
printf "%s=\"%s\"\n" "$var" "$val" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# include parse_yaml function | |
. "$(dirname "$0")"/parse_yaml.sh | |
# read yaml file | |
eval $(parse_yaml config.yaml "CONFIG") | |
# access yaml content | |
echo $CONFIG_name | |
echo $CONFIG_database_host |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sequences not implemented yet.
should work with sh/dash also.
quite slow but works