Working with YAML

How to:

Working directly with YAML in Bash requires a bit of ingenuity since Bash does not have built-in support for parsing YAML. However, you can use external tools like yq (a lightweight and portable command-line YAML processor) to interact with YAML files efficiently. Let’s go through some common operations:

Installing yq:

Before diving into the examples, ensure you have yq installed. You can usually install it from your package manager, for example, on Ubuntu:

sudo apt-get install yq

Or you can download it directly from its GitHub repository.

Reading a value:

Consider you have a file named config.yaml with the following content:

  host: localhost
  port: 5432
  name: admin
  password: secret

To read the database host, you can use yq as follows:

yq e '' config.yaml

Sample Output:


Updating a value:

To update the user’s name in config.yaml, use the yq eval command with the -i (in-place) option:

yq e ' = "newadmin"' -i config.yaml

Verify the change with:

yq e '' config.yaml

Sample Output:


Adding a new element:

To add a new element under the database section, like a new field timeout:

yq e '.database.timeout = 30' -i config.yaml

Checking the contents of the file will confirm the addition.

Deleting an element:

To remove the password under user:

yq e 'del(.user.password)' -i config.yaml

This operation will remove the password field from the configuration.

Remember, yq is a powerful tool and has a lot more capabilities, including converting YAML to JSON, merging files, and even more complex manipulations. Refer to the yq documentation for further exploration.