Bash Script to Read YAML File Easily
Use a Bash script with
grep and sed to extract values from a YAML file, for example: value=$(grep '^key:' file.yaml | sed 's/^key:[[:space:]]*//') reads the value of 'key'.Examples
Inputfile.yaml content:
name: Alice
OutputAlice
Inputfile.yaml content:
user: bob
age: 30
Outputbob
Inputfile.yaml content:
empty_key:
Output
How to Think About It
To read a YAML file in Bash, think of it as a text file where each line has a key and a value separated by a colon. You can find the line starting with the key you want using
grep, then remove the key and colon to get the value using sed or similar tools.Algorithm
1
Get the YAML file path and the key to read.2
Search the file for the line starting with the key followed by a colon.3
Extract the part after the colon, trimming spaces.4
Return or print the extracted value.Code
bash
#!/bin/bash file="file.yaml" key="name" value=$(grep "^$key:" "$file" | sed -e "s/^$key:[[:space:]]*//") echo "$value"
Output
Alice
Dry Run
Let's trace reading the key 'name' from file.yaml containing 'name: Alice'.
1
Search for key line
grep '^name:' file.yaml returns 'name: Alice'
2
Extract value
sed removes 'name: ' leaving 'Alice'
3
Print value
echo prints 'Alice'
| Step | Command Output |
|---|---|
| grep '^name:' file.yaml | name: Alice |
| sed 's/^name:[[:space:]]*//' | Alice |
| echo | Alice |
Why This Works
Step 1: Find the key line
The grep command looks for the line starting with the key and a colon to isolate the correct line.
Step 2: Remove the key and colon
The sed command deletes the key and colon, leaving only the value part.
Step 3: Output the value
The script prints the extracted value so you can use it in your Bash script.
Alternative Approaches
Using yq command-line tool
bash
value=$(yq e '.name' file.yaml) echo "$value"
Requires installing yq but handles complex YAML safely and easily.
Using awk to parse YAML
bash
value=$(awk -F": " '/^name:/ {print $2}' file.yaml) echo "$value"
Simple and fast for flat YAML but less flexible for nested structures.
Complexity: O(n) time, O(1) space
Time Complexity
The script reads the file line by line once, so time grows linearly with file size.
Space Complexity
Uses constant extra space for variables; no large data structures stored.
Which Approach is Fastest?
Using grep and sed is fast for simple YAML; yq is slower but safer for complex files.
| Approach | Time | Space | Best For |
|---|---|---|---|
| grep + sed | O(n) | O(1) | Simple flat YAML |
| yq tool | O(n) | O(1) | Complex or nested YAML |
| awk | O(n) | O(1) | Simple key-value extraction |
For complex YAML, use a dedicated parser like yq instead of text tools.
Beginners often forget to handle spaces after the colon, causing wrong value extraction.