Bash:
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 yqOr you can download it directly from its GitHub repository.
Reading a value:
Consider you have a file named config.yaml with the following content:
database:
host: localhost
port: 5432
user:
name: admin
password: secretTo read the database host, you can use yq as follows:
yq e '.database.host' config.yamlSample Output:
localhostUpdating a value:
To update the user’s name in config.yaml, use the yq eval command with the -i (in-place) option:
yq e '.user.name = "newadmin"' -i config.yamlVerify the change with:
yq e '.user.name' config.yamlSample Output:
newadminAdding a new element:
To add a new element under the database section, like a new field timeout:
yq e '.database.timeout = 30' -i config.yamlChecking 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.yamlThis 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.