DEV Community

Hai Vu
Hai Vu

Posted on

1

How to Parse bash Variables

The Problem

I sometimes need to parse a shell script to pick out variables declarations. Consider the following bash script, myscript.sh:

echo hello
server="server1.example.com"
port=8899
echo done
Enter fullscreen mode Exit fullscreen mode

The Solution

The first step is read the contents of the script:

with open("myscript.sh") as stream:
    contents = stream.read().strip()
print(contents)
Enter fullscreen mode Exit fullscreen mode
echo hello
server="server1.example.com"
port=8899
echo done
Enter fullscreen mode Exit fullscreen mode

Next, we would pick out those lines which contains the variable declaration using regular expression:

import re

var_declarations = re.findall(r"^[a-zA-Z0-9_]+=.*$", contents, flags=re.MULTILINE)
print(var_declarations)
Enter fullscreen mode Exit fullscreen mode
['server="server1.example.com"', 'port=8899']
Enter fullscreen mode Exit fullscreen mode

Finally, we use the csv library to parse these declarations and return a dictionary:

import csv
reader = csv.reader(var_declarations, delimiter="=")
vars = dict(reader)
print(vars)
Enter fullscreen mode Exit fullscreen mode
{'server': 'server1.example.com', 'port': '8899'}
Enter fullscreen mode Exit fullscreen mode

Putting it all together:

import re
import csv

def parse_bash_vars(path: str) -> dict:
    """
    Parses a bash script and returns a dictionary representing the
    variables declared in that script.

    :param path: The path to the bash script
    :return: Variables as a dictionary
    """
    with open(path) as stream:
        contents = stream.read().strip()

    var_declarations = re.findall(r"^[a-zA-Z0-9_]+=.*$", contents, flags=re.MULTILINE)
    reader = csv.reader(var_declarations, delimiter="=")
    bash_vars = dict(reader)
    return bash_vars
Enter fullscreen mode Exit fullscreen mode

Test it out:

parse_bash_vars("myscript.sh")
Enter fullscreen mode Exit fullscreen mode
{'server': 'server1.example.com', 'port': '8899'}
Enter fullscreen mode Exit fullscreen mode




Conclusion

When mentioning the csv library, most thinks of it as a way to parse comma-separated-values files, but it has other uses such as parsing the bash variables or parsing /etc/os-release file.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay