Skip to main content

Command Palette

Search for a command to run...

parse YAML on bash script

A fast way to parse yaml file inside a bash/shell script

Updated
β€’1 min read
parse YAML  on bash script
E

Linux power user since 2003. IT Manager, DevOps/SRE, Systems Administrator, and teacher. Bass player, Krav Maga practitioner, and sport shooter.

https://esli.blog || https://esli.cafe

How to parse and use the YAML file in bash/shell script

Create this function:

function parse_yaml {
    local prefix=$2
    local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
    sed -ne "s|^\($s\):|\1|" \
        -e "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])("_")}
            printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3);
        }
    }'
}

At the beginning of your script, call eval to concate arguments.

eval $(parse_yaml config.yml "CONFIG_")

This eval line will put CONFIG_ in front of each variable found in config.yml (it is the \$2 and $prefix in function parse_yaml) line 4 and line 15 from my parse_example.sh .

The config.yaml is on the same path that the .sh. Therefore, you can create or modify the function to another YAML file (or add a variable) and change the prefix.

Each value from yml will be separated by "_" on your script call.

Example:

  keyA:
    elementB: valueB

And echo "$CONFIG_keyA_elementB" will return valueB

Repo parse_yaml-with-bash:

Tech

Part 20 of 50

Technical topics. Code, Linux, Network... Exercising the Tech Writer and teacher in me. Articles covering topics from across the entire OSI layer. Artigos passando por assuntos de toda a camada OSI.

Up next

Instalando o R no Linux

Instalando e Iniciando R-lang no Linux