Parse the configuration file, don't execute it.
I'm currently writing an application at work that uses an extremely simple XML configuration:
<config>
<username>username-or-email</username>
<password>the-password</password>
</config>
In the shell script (the "application"), this is what I do to get at the username (more or less, I've put it in a shell function):
username=$( xmlstarlet sel -t -v '/config/username' "$config_file" )
The xmlstarlet
command is XMLStarlet, which is available for most Unices. On some systems, it's installed as xml
.
I'm using XML since other parts of the application also deals with data encoded in XML files, so it was easiest.
If you prefer JSON, there's jq
which is an easy to use shell JSON parser.
My configuration file would look something like this in JSON:
{
"username": "username-or-email",
"password": "the-password"
}
And then I'd be getting the username in the script:
username=$( jq -r .username "$config_file" )
There is also TOML ("Tom's Obvious Minimal Language"), with parsers for several languages. My personal favorite parser, tomlq
, is part of the yq
distribution from https://kislyuk.github.io/yq/ (uses jq
behind the scenes).
The TOML version of your configuration file would look like
username = "username-or-email"
password = "the-password"
(the strings would be JSON-encoded)... and getting data out from it would be as simple as in the JSON case (since tomlq
is built on top of jq
):
username=$( tomlq -r .username "$config_file" )
abcde
also does it this way and that is a quite big program (for a shell script). You can have a look at it here.