Fish Shell:
Working with YAML
How to:
Fish Shell doesn’t have built-in support for parsing YAML, but you can utilize third-party tools like yq (a lightweight and portable command-line YAML processor) to handle YAML data.
Installation of yq (if not already installed):
sudo apt-get install yqReading a value from a YAML file:
Suppose you have a YAML file config.yaml with the following content:
database:
host: localhost
port: 3306To read the database host, you’d use:
set host (yq e '.database.host' config.yaml)
echo $hostSample output:
localhostUpdating a value in a YAML file:
To update the port to 5432, use:
yq e '.database.port = 5432' -i config.yamlVerify the update:
yq e '.database.port' config.yamlSample output:
5432Writing a new YAML file:
For creating a new new_config.yaml with predefined content:
echo "webserver:
host: '127.0.0.1'
port: 8080" | yq e -P - > new_config.yamlThis uses yq to process and pretty-print (-P flag) a string into a new YAML file.
Parsing complex structures: If you have a more complex YAML file and need to fetch nested arrays or objects, you can:
echo "servers:
- name: server1
ip: 192.168.1.101
- name: server2
ip: 192.168.1.102" > servers.yaml
yq e '.servers[].name' servers.yamlSample output:
server1
server2Using yq, Fish Shell makes it straightforward to navigate through YAML documents and manipulate them for various automation and configuration tasks.