Skip to content

Instantly share code, notes, and snippets.

@mabe-at
Last active September 24, 2022 13:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mabe-at/befb55910c6892789128 to your computer and use it in GitHub Desktop.
Save mabe-at/befb55910c6892789128 to your computer and use it in GitHub Desktop.
Parse YAML into shell variables using shyaml
---
name: 'Max Mustermann'
database:
host: 'localhost'
database: 'mydb'
#!/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"
}
#!/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
@mabe-at
Copy link
Author

mabe-at commented Dec 7, 2015

sequences not implemented yet.
should work with sh/dash also.
quite slow but works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment